Head First设计模式-工厂模式
一、整体代码
PizzaStore.java
public class PizzaTestDrive { public static void main(String[] args) {PizzaStore nyStore = new NYPizzaStore();PizzaStore chicagoStore = new ChicagoPizzaStore(); Pizza pizza = nyStore.orderPizza("cheese");System.out.println("Ethan ordered a " + pizza.getName() + "\n"); pizza = chicagoStore.orderPizza("cheese");System.out.println("Joel ordered a " + pizza.getName() + "\n");pizza = nyStore.orderPizza("clam");System.out.println("Ethan ordered a " + pizza.getName() + "\n"); pizza = chicagoStore.orderPizza("clam");System.out.println("Joel ordered a " + pizza.getName() + "\n");}}
二、总结
1、工厂方法模式定义了对象的接口,但由子类决定实例化的类是哪一个。工厂方法模式让类的实例化推迟到子类。
2、抽象类和接口可以实现多态,这样才保证了面向对象的可扩展性,封装变化,松耦合等特性。设计模式几乎都在与抽象类和接口打交到,用的越多,程序可扩展性越好。