3.3 抽象工厂模式
抽象工厂模式是什么?
抽象工厂是应对产品族概念的。比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。
UML类图:
类图代码:
ProductA
public interface ProductA { public void operation1(); public void operation2(); }
ProductB
public interface ProductB { public void operation1(); public void operation2(); }
ConcreateProductA1
public class ConcreateProductA1 implements ProductA { public void operation1() { System.out.println("ConcreateProductA1 -> operation1"); } public void operation2() { System.out.println("ConcreateProductA1 -> operation2"); } }
ConcreateProductA2
public class ConcreateProductA2 implements ProductA { public void operation1() { System.out.println("ConcreateProductA2 -> operation1"); } public void operation2() { System.out.println("ConcreateProductA2 -> operation2"); } }
ConcreateProductB1
public class ConcreateProductB1 implements ProductB { public void operation1() { System.out.println("ConcreateProductB1 -> operation1"); } public void operation2() { System.out.println("ConcreateProductB1 -> operation2"); } }
ConcreateProductB2
public class ConcreateProductB2 implements ProductB { public void operation1() { System.out.println("ConcreateProductB1 -> operation1"); } public void operation2() { System.out.println("ConcreateProductB1 -> operation2"); } }
Factory
public interface Factory { public ProductA createProductA(); public ProductB createProductB(); }
ConcreateFactoryA
public class ConcreateFactoryA implements Factory{ public ProductA createProductA() { return new ConcreateProductA1(); } public ProductB createProductB() { return new ConcreateProductB1(); } }
ConcreateFactoryB
public class ConcreateFactoryB implements Factory{ public ProductA createProductA() { return new ConcreateProductA2(); } public ProductB createProductB() { return new ConcreateProductB2(); } }
Client
public class Client { public static void main(String[] args) { Factory factoryA = new ConcreateFactoryA(); ProductA productA1 = factoryA.createProductA(); productA1.operation1(); productA1.operation2(); ProductB productB1 = factoryA.createProductB(); productB1.operation1(); productB1.operation2(); Factory factoryB = new ConcreateFactoryB(); ProductA productA2 = factoryB.createProductA(); productA2.operation1(); productA2.operation2(); ProductB productB2 = factoryB.createProductB(); productB2.operation1(); productB2.operation2(); } }
执行结果
ConcreateProductA1 -> operation1 ConcreateProductA1 -> operation2 ConcreateProductB1 -> operation1 ConcreateProductB1 -> operation2 ConcreateProductA2 -> operation1 ConcreateProductA2 -> operation2 ConcreateProductB1 -> operation1 ConcreateProductB1 -> operation2
抽象工厂模式应用于哪些场景?
(1)工厂方法模式是一个工厂生产一类产品,而抽象工厂模式是一个工厂需要生产两种或者两种以上的不同产品。