HeadFirst设计模式---抽象工厂

类图

HeadFirst设计模式---抽象工厂

抽象披萨商店类

public abstract class PizzaStore {
    public void orderPizza(String type) {
        AbstractPizza abstractPizza = this.createPizza(type);
        abstractPizza.prepare();
        abstractPizza.cut();
        abstractPizza.bake();
        abstractPizza.box();
    } 
    //子类实现
    public abstract AbstractPizza createPizza(String type);

}

实体披萨商店

public class ChicagoPizzaStore extends PizzaStore {
    public AbstractPizza createPizza(String type) {
       AbstractPizza pizza = null;
        if ("cheesePizza".equals(type)) {
            pizza = new CheeseAbstractPizza();
        } else if ("greekPizza".equals(type)) {
            pizza = new GreekAbstractPizza();
        } else if ("pepperoniPizza".equals(type)) {
            pizza = new PepperoniAbstractPizza();
        }
        return pizza;
    }
}
public class NYPizzaStore extends PizzaStore {
    public AbstractPizza createPizza(String type) {
       AbstractPizza pizza = null;
        if ("cheesePizza".equals(type)) {
            pizza = new CheeseAbstractPizza();
        } else if ("greekPizza".equals(type)) {
            pizza = new GreekAbstractPizza();
        } else if ("pepperoniPizza".equals(type)) {
            pizza = new PepperoniAbstractPizza();
        }
        return pizza;
    }
}

抽象披萨

public abstract class AbstractPizza {
    public void prepare() {
        System.out.println("prepare pizza");
    }
    public void bake(){
        System.out.println("bake pizza");
    }
    public void cut(){
        System.out.println("cut pizza");
    }
    public void box(){
        System.out.println("pizza box");
    }
}

实体披萨

public class CheeseAbstractPizza extends AbstractPizza {
    @Override
    public void prepare() {
        System.out.println("prepare CheesePizza");
    }
}
public class GreekAbstractPizza extends AbstractPizza {
    @Override
    public void prepare() {
        System.out.println("prepare GreekPizza");
    }
}
public class PepperoniAbstractPizza extends AbstractPizza {
    @Override
    public void prepare() {
        System.out.println("prepare PepperoniPizza");
    }
}

运行

public class Tester {
    public static void main(String[] args) {
        PizzaStore pizzaStore = new NYPizzaStore();
        PizzaStore pizzaStore1 = new ChicagoPizzaStore();
        System.out.println(pizzaStore.createPizza("greekPizza"));
        System.out.println(pizzaStore1.createPizza("pepperoniPizza"));
    }
}

总结

  1. 面向接口编程,扩展开放
  2. 父类不需要知道子类的具体实现
上一篇:photoshop 把美女头像转成精细的仿手绘效果


下一篇:设计模式 | 第二篇:观察者模式