Sunday, June 22, 2014

The Factory Method Pattern in C#

If you are not familiar with the Factory Method pattern, it is a well known design pattern officially defined as the following:
The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate.  Factory Method lets a class defer instantiation to subclasses.  (Head First Design Patterns-the factory pattern)
In the example provided in the book “Head First Design Patterns”, essentially a Pizza Store has grown into a franchise that needs to create different styles of pizzas based on different Pizza Stores in the franchise.  So how is that handled?  Essentially, allowing each Pizza Store in the franchise decide how to make the various styles of pizzas they will be creating (through subclasses/inheritance) but providing the overall framework for how the pizzas will be created.
The original source code is provided in Java in this book, therefore, I have provided a C# version for .NET Developers who want to begin using this pattern in their own development:
void Main()


    PizzaStore nyStore = new NYPizzaStore();

    Pizza pizza = nyStore.orderPizza("cheese");

    Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");





// Define other methods and classes here

public abstract class Pizza


protected string name;

protected string dough;

protected string sauce;

protected ArrayList toppings = new ArrayList();


public void prepare()


    Console.WriteLine("Preparing " + name);

    Console.WriteLine("Tossing dough....");

    Console.WriteLine("Adding sauce...");

    Console.WriteLine("Adding toppings:");

    for (int i=0; i< toppings.Count; i++)


      Console.WriteLine(" " + toppings[i]);




public void bake()


    Console.WriteLine("Bake for 25 minutes at 350");



public void cut()


      Console.WriteLine("Cutting the pizza into diagonal slices");



public void box()


      Console.WriteLine("Place piza in official PizzaStore box");



public string Name




        return name;


    }//property: Name



public class NYStyleCheesePizza: Pizza


    public NYStyleCheesePizza()


          name = "NY Style Sauce and Cheese Pizza";

          dough = "Thin Crust Dough";

          sauce = "Marinara Sauce";

          toppings.Add("Grated Reggiano Cheese");


    }//class: NYStyleCheesePizza


public abstract class PizzaStore


  public Pizza orderPizza(string type)


    Pizza pizza;


    pizza = createPizza(type);






    return pizza;



    protected abstract Pizza createPizza(string type);

}//class: PizzaStore


public class NYPizzaStore: PizzaStore


    protected override Pizza createPizza(string item)


    if (item.Equals("cheese"))


     return new NYStyleCheesePizza();




      return null;



}//class: NYPizzaStore


No comments:

Post a Comment