Wednesday, 14 October 2009

Design Pattern 3 - Factory Method Pattern

The Factory Method pattern allows for the instantiation of objects at runtime. We can think of Factory Pattern as a factory which is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Obviously, a factory is not needed to make an object. A simple call to new will do it for you. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific subclasses which create them. In addition, one principle in OOP programming is to reduce coupling. Avoid using new key work means we also avoid the dependency between classes which make it much easier for unit testing.



There is one very good article in Wikipedia about Factory Method pattern, where using an example of Pizza factory produce different type of Pizzas. The code is in Java, with a little effort I have re-written it in C# as the code shown below:

using System;

namespace FactoryMethodPattern
{
abstract class Pizza
{
public abstract double getPrice();
}

class HamAndMushroomPizza : Pizza
{
public override double getPrice()
{
return 8.5;
}
}

class DeluxePizza : Pizza
{
public override double getPrice()
{
return 10.5;
}
}

class HawaiianPizza : Pizza
{
public override double getPrice()
{
return 11.5;
}
}

class PizzaFactory
{
public enum PizzaType
{
HamMushroom,
Deluxe,
Hawaiian
}

public static Pizza createPizza(PizzaType pizzaType)
{
switch (pizzaType)
{
case PizzaType.HamMushroom:
return new HamAndMushroomPizza();
case PizzaType.Deluxe:
return new DeluxePizza();
case PizzaType.Hawaiian:
return new HawaiianPizza();
default:
return null;
}
}
}

class Program
{
static void Main(string[] args)
{
// Loop with foreach through a Enum
foreach (PizzaFactory.PizzaType pizzaType in
Enum.GetValues(typeof(PizzaFactory.PizzaType)))
{
Console.WriteLine("Price of " + pizzaType + " is £"
+ PizzaFactory.createPizza(pizzaType).getPrice());
}
}
}
}



Reference: Factory method pattern in Wikipedia.

No comments:

Post a Comment