/* * 结合工厂方法模式中的例子,各分部的披萨店快要开张了,但是不同地方的披萨 * 所需的原料都各不相同,同样的芝士披萨,纽约偏甜,芝加哥却偏酸。抽象工厂 * 模式很好地提供了如何针对于不同的地方供应不一样的原料。 */ public class PizzaStore { PizzaFactory pizzaFactory; public PizzaStore(PizzaFactory pizzaFactory) { this.pizzaFactory = pizzaFactory; } public void orderPizza(String item) { Pizza pizza = pizzaFactory.createPizza(item); pizza.display(); } }
// AbstractFactory - 抽象工厂 public interface class PizzaIngredientFactory { // AbstractProduct - 抽象产品 public Cheese createCheese(); public Sauce createSauce(); }
// ConcreteFactory - 具体工厂 // 纽约原料工厂 public class NewYorkIngredientFactory implements PizzaIngredientFactory { // ConcreteProduct - 具体产品 @Override public Cheese createCheese() { System.out.println("reggiano cheese"); } @Override public Sauce createSauce() { System.out.println("marinara sauce"); } }
// 芝加哥原料工厂 public class ChicagoIngredientFactory implements PizzaIngredientFactory { @Override public Cheese createCheese() { System.out.println("sugar cheese"); } @Override public Sauce createSauce() { System.out.println("tomato sauce"); } }
// 举一生产Pizza工厂为例,进行优化改进 public class NewYorkPizzaFactory extends PizzaFactory { PizzaIngredientFactroy ingredientFactory; public NewYorkPizzaFactory(PizzaIngredientFactroy ingredientFactory) { this.ingredientFactory = ingredientFactory; } public Pizza createPizza(String item) { if (item.equals("cheese")) { // 此处将纽约原料工厂的引用转交给NewYorkCheesePizza对象处理,让其自主调用需要的材料 return new NewYorkCheesePizaa(ingredientFactory); } } }
// 测试类 public class Test { public static void main(String[] args) { PizzaFactory newYorkPizzaFactory = new NewYorkPizzaFactory(new NewYorkPizzaFactory()) PizzaStore newYorkStore = new PizzaStore(newYorkPizzaFactory); newYorkStore.orderPizza("cheese"); PizzaFactory chiCagoPizzaFactory = new ChiCagoPizzaFactory(new ChiCagoPizzaFactory()) PizzaStroe chicagoStore = new PizzaStore(chiCagoPizzaFactory); chicagoStore.orderPizza("cheese"); } }