Home > Development > Factory Method

Factory Method

September 11, 2010 Leave a comment Go to comments

Definition

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

UML

namespace FactoryMethod
{

    public abstract class Manufacturer
    {  
    }

    public class Nissan : Manufacturer{}

    public class Mitsubishi : Manufacturer{}

    public abstract class Car
    {
        public abstract Manufacturer GetManufacturer();
    }

    public class Pulsar : Car
    {
        public override Manufacturer GetManufacturer()
        {
            return new Nissan();
        }
    }

    public class Lancer : Car
    {
        public override Manufacturer GetManufacturer()
        {
            return new Mitsubishi();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Lancer l = new Lancer();
            AcceptManufacturer(l.GetManufacturer());
        }

        public static void AcceptManufacturer(Manufacturer manufacturer)
        {
            
        }
    }
}

As you can see from the code, Car defines a method, GetManufacturer which is implemented by the derived classes to return a specialized version of Manufacturer. Pretty simple really.

Blair…

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: