抽象工厂模式结构:
AbstractFactory:抽象工厂
ConcreteFactory:具体工厂
AbstractProduct:抽象产品
Product:具体产品
UML图:
例子代码:
public interface AbstractFactory { AbstractProduct createProductA(); AbstractProduct createProductB(); }
public class ConceteFacotry1 implements AbstractFactory { @Override public AbstractProduct createProductA() { return new ProductA1(); } @Override public AbstractProduct createProductB() { return new ProductA2(); } }
public class ConcreteFactory2 implements AbstractFactory { @Override public AbstractProduct createProductA() { return new ProductA2(); } @Override public AbstractProduct createProductB() { return new ProductB2(); } }
public interface AbstractProduct { void use(); }public interface AbstactProductA extends AbstractProduct{ }public interface AbstractProductB extends AbstractProduct { }public class ProductA1 implements AbstactProductA { @Override public void use() { System.out.println("生产商品A1"); } }public class ProductA2 implements AbstactProductA { @Override public void use() { System.out.println("生产商品A2"); } }public class ProductB1 implements AbstractProductB { @Override public void use() { System.out.println("生产商品B1"); } }public class ProductB2 implements AbstractProductB { @Override public void use() { System.out.println("生产商品B2"); } }结果打印:public class AbstractFactoryTest { public static void main(String[] args) { AbstractFactory factory1 = new ConceteFacotry1(); AbstractFactory factory2 = new ConcreteFactory2(); factory1.createProductA().use(); factory1.createProductB().use(); factory2.createProductA().use(); factory2.createProductB().use(); } }