我已阅读有关子类创建所需对象的工厂方法和抽象工厂具有具体类创建所需对象的方法
工厂方法
public class PizzaStore {
public Pizza orderPizza(String type) {
Pizza pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
}
abstract Pizza createPizza(String type);
}
public NewYorkPizzaStore extends PizzaStore {
public Pizza createPizza(String type) {
Pizza pizza = null;
if("cheese".equals(type)) {
pizza = new CheesePizza();
}
else if("onion".equals(type)) {
pizza = new OnionPizza();
}
return pizza;
}
}
public class pizzaTestDriveByFactoryMethod() {
public static void main(String args[]) {
PizzaStore ps = new NewYorkPizzaStore();
ps.orderPizza("cheese");
}
}
使用工厂
public class NewYorkPizzaFactory extends PizzaFactory {
public Pizza createPizza(String pizza) {
Pizza pizza = null;
if("cheese".equals(type)) {
pizza = new CheesePizza();
} else if("onion".equals(type)) {
pizza = new OnionPizza();
}
return pizza;
}
}
public class PizzaStore {
PizzaFactory factory;
public PizzaStore(PizzaFactory factory) {
this.factory = factory
}
public Pizza orderPizza(String type) {
Pizza pizza = factory.createPizza(type)
pizza.prepare();
pizza.bake();
pizza.cut();
return pizza;
}
}
public class pizzaTestDriveByAbstractFactory() {
public static void main(String args[]) {
PizzaFactory nwFactory = new NewYorkPizzaFactory();
PizzaStore ps = new PizzaStore(nwFactory);
ps.orderPizza("cheese");
}
}
使用工厂方法和抽象工厂实现的相同用例。为什么应该有 FactoryMethod 而不是使用 Abstract Factory 或 Utility Factory(例如 Chicago Factory/NewYorkFactory)。在哪种情况下工厂方法对抽象方法有用?