Does this factory method pattern example violate open-close?
- by William
In Head-First Design Patterns, they use a pizza shop example to demonstrate the factory method pattern.
public abstract class PizzaStore {
public Pizza orderPizza(String type) {
Pizza pizza;
pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
abstract Pizza createPizza(String type)
}
public class NYPizzaStore extends PizzaStore {
Pizza createPizza(String item) {
if (item.equals("cheese") {
return new NYStyleCheesePizza();
} else if (item.equals("veggie")) {
return new NYStyleVeggiePizza();
} else if (item.equals("clam")) {
return new NYStyleClamPizza();
} else if (item.equals("pepperoni")) {
return new NYStylePepperioniPizza();
} else return null;
}
}
I don't understand how this pattern is not violating open-close. What if we require a beef Pizza, then we must edit the if statement in the NYPizzaStore class.