Does this factory method pattern example violate open-close?
Posted
by
William
on Programmers
See other posts from Programmers
or by William
Published on 2014-08-19T18:29:56Z
Indexed on
2014/08/19
22:32 UTC
Read the original article
Hit count: 240
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.
© Programmers or respective owner