Sunday, May 30, 2010

Simple Factory

1. The simple Factory Method is not a design pattern but more of a programming idiom.

2.

a. The client of factory uses factory to create instances of concrete classes.
b. The create() method is often declared statically.



3. Example

 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;
}
}


Drawbacks

1. Number of implementation classes is hardwired into the factory method. Therefore, even though there is an interface for the implementation objects, it's impossible for the factory method to return an implementation class that it does not know about. This limits extensibility, especially in the case of a public API and application frameworks, where the ability to dynamically introduce new implementation classes is not only desired, but often expected to achieve a certain degree of flexibility.

2. Even if the ability to dynamically introduce new implementations existed, the client application would still need to know which class to ask for. This eliminates some of the flexibility that the factory class was supposed to provide.

No comments:

Post a Comment