The disadvantage of declaring static method in Factory class, according to Head First Design Pattern - "you can't subclass and change the behavior of getPizza method". getPizza method is used by Factory class to decide which type of object to return. If I understand correctly, my class is
public class PizzaFactory {
public static Pizza getPizza(String type) {
if (type.equals("cheese"))
return new CheesePizza();
else if (type.equalsIgnoreCase("thisCrust"))
return new ThinCrustPizza();
return null;
}
}
Even though the method is static I can always create a subclass like -
public class DelhiPizzaFactory extends PizzaFactory {
public static Pizza getPizza(String type) {
if (type.equals("cheese"))
return new CheesePizza();
else if (type.equalsIgnoreCase("thisCrust"))
return new ThinCrustPizza();
return null;
}
}
I can use both the superclass and subclass interchangeably.
public class PizzaStore {
Pizza pizza;
public void orderPizza(String type) {
pizza = DelhiPizzaFactory.getPizza(type);
pizza.prepare();
pizza.bake();
}
}
So what is the disadvantage?
Aucun commentaire:
Enregistrer un commentaire