/************************************************************************* * 创建型: Singleton, Builder, Abstract Factory, Factory Method, Prototype * 结构型: Decorator, Composite, Proxy, Adapter, Facade * 行为型: Template Method, Iterator, Observer, Strategy, Command, ChainOR */ package factory; /** * @author jiq * 类型:Creational * 定义: 抽象工厂模式(Abstract Factory) 提供一个接口,用于创建相关或者依赖对象的家族, * 而不需要指明具体类。 * OO设计原则: 要依赖抽象,而不要依赖具体类 * 与工厂方法关系:抽象工厂模式用到了工厂方法模式。 * 缺点: 如果要拓展创建的产品,需要更改抽象工厂接口。 */ /**(抽象工厂) * 抽象的创建各种原料的工厂 * 但是创建的具体原料是什么,由其子类决定 * */ interface PizzaIngredientFactory{ public Dough createDough(); //工厂方法 public Sauce createSauce(); //工厂方法 public Cheese createCheese(); //工厂方法 } /** 抽象工厂的子类,决定创建什么样的具体产品 */ class NYPizzaIndigredientFactory implements PizzaIngredientFactory{ public Cheese createCheese() { return new QQQCheese(); } public Dough createDough() { return new YYYDough(); } public Sauce createSauce() { return new WWWSauce(); } } /** 抽象工厂的子类,决定创建什么样的具体产品 */ class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory{ public Cheese createCheese() { return new EEECheese(); } public Dough createDough() { return new XXXDough(); } public Sauce createSauce() { return new WWWSauce(); } } /////////////////////////////////////////////////////////////// /** * 抽象的产品接口 * */ interface Dough{} interface Sauce{} interface Cheese{} class XXXDough implements Dough{} class YYYDough implements Dough{} class WWWSauce implements Sauce{} class QQQCheese implements Cheese{} class EEECheese implements Cheese{} //测试类 public class AbstractFactoryTest { public static void main(String[] args) { PizzaIngredientFactory nyfactory = new NYPizzaIndigredientFactory(); nyfactory.createCheese(); nyfactory.createDough(); nyfactory.createSauce(); } }