Skip to content
May 27, 2010 / prilandtechnology

Factory Method

The factory method pattern is an object-oriented design pattern to implement the concept of factories.

Like other creation’s patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Outside the scope of design patterns, the term factory method can also refer to a method of a factory whose main purpose is creation of objects.

public interface IPizza
{
    decimal Price { get; }
}
public class HamAndMushroomPizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 8.5m;
        }
    }
}
public class DeluxePizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 10.5m;
        }
    }
}
public class HawaiianPizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 11.5m;
        }
    }
}
public class PizzaFactory
{
    public enum PizzaType
    {
        HamMushroom,
        Deluxe,
        Hawaiian
    }
    public static IPizza CreatePizza(PizzaType pizzaType)
    {
        IPizza ret = null;
        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                ret = new HamAndMushroomPizza();
                break;
            case PizzaType.Deluxe:
                ret = new DeluxePizza();
                break;
            case PizzaType.Hawaiian:
                ret = new HawaiianPizza();
                break;
            default:
                throw new ArgumentException("The pizza type " + pizzaType + " is not recognized.");
        }
        return ret;
    }
}
public class PizzaLover
{
    public static void Main(string[] args)
    {
        Dictionary
 pizzas = new Dictionary
();
        foreach (PizzaFactory.PizzaType pizzaType in Enum.GetValues(typeof(PizzaFactory.PizzaType)))
        {
            pizzas.Add(pizzaType, PizzaFactory.CreatePizza(pizzaType));
        }
        foreach (PizzaFactory.PizzaType pizzaType in pizzas.Keys)
        {
            System.Console.WriteLine("Price of {0} is {1}", pizzaType, pizzas[pizzaType].Price);
        }
    }
}

Output:
Price of HamMushroom is 8.5
Price of Deluxe is 10.5
Price of Hawaiian is 11.5

Advertisements

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: