【设计模式】Headfirst设计模式——简单工厂运行代码
public class Pizza { public void prepare() { System.out.println("preparing..."); } public void bake() { System.out.println("baking..."); } public void cut() { System.out.println("cutting..."); } public void box() { System.out.println("boxing..."); } public static void main(String[] args) { SimpleFactory sim=new SimpleFactory(); PizzaStore pizzastore=new PizzaStore(sim); System.out.println("1st pizza"); pizzastore.orderPizza("cheese"); System.out.println("2rd pizza"); pizzastore.orderPizza("veggie"); } } class CheesePizza extends Pizza{ String type="Cheese"; CheesePizza(){ System.out.println("cheesepizza created"); } } class ClamPizza extends Pizza{ String type="Clam"; ClamPizza(){ System.out.println("clampizza created"); } } class VeggiePizza extends Pizza{ String type="Veggie"; VeggiePizza(){ System.out.println("veggiepizza created"); } } class SimpleFactory { public Pizza createPizza(String type) { Pizza pizza = null; if (type.equals("cheese")) { pizza = new CheesePizza(); } else if (type.equals("clam")) { pizza = new ClamPizza(); } else if (type.equals("veggie")) { pizza = new VeggiePizza(); } return pizza; } } class PizzaStore { SimpleFactory simpleFactory; public PizzaStore(SimpleFactory simpleFactory) { this.simpleFactory = simpleFactory; } Pizza orderPizza(String type) { Pizza pizza = null; pizza = simpleFactory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } }