1.介绍
它是定义一个创建对象的接口,但由子类决定要实例化的类是哪一个,工厂方法让类把实例化推迟到子类中。
2.小栗子
Pizza店做Pizza
3.代码实现
// Pizza抽象类
public abstract class Pizza {
protected PizzaIngredientFactory factory = null;
public Pizza(PizzaIngredientFactory factory) {
this.factory = factory;
}
public abstract String getName();
public void prepare() {
System.out.println("Dough:" + factory.createDough().getName());
System.out.println("Sauce:" + factory.createSauce().getName());
System.out.println(this.getName() + " prepare success.");
}
}
// 纽约Pizza
public class NYPizza extends Pizza {
public NYPizza(PizzaIngredientFactory factory) {
super(factory);
}
@Override
public String getName() {
return "NY Pizza";
}
}
// 西雅图Pizza
public class SeattlePizza extends Pizza {
public SeattlePizza(PizzaIngredientFactory factory) {
super(factory);
}
@Override
public String getName() {
return "Seattle Pizza";
}
}
// Pizza店 做Pizza
public abstract class PizzaStore {
public void orderPizza(PizzaIngredientFactory factory) {
Pizza pizza = createPizza(factory);
pizza.prepare();
}
// 工厂方法模式
protected abstract Pizza createPizza(PizzaIngredientFactory factory);
}
// 纽约PizzaStore
public class NYPizzaStore extends PizzaStore {
@Override
protected Pizza createPizza(PizzaIngredientFactory factory) {
return new NYPizza(factory);
}
}
4.测试
public class FactoryMethodPatternDemo {
public static void main(String[] args) {
PizzaIngredientFactory nyFactory = new NYPizzaIngredientFactory();
PizzaIngredientFactory seattleFactory = new SeattlePizzaIngredientFactory();
PizzaStore pizzaStore = new NYPizzaStore();
pizzaStore.orderPizza(seattleFactory);
pizzaStore.orderPizza(nyFactory);
}
}
5.总结
纽约可以做纽约/西雅图等地区风格的Pizza,而且Pizza本身风格也是可以扩展的。
源码地址:https://gitee.com/jsjack_wang/JavaDemo