1. 抽象工厂模式能够说是简单工厂模式的扩展,它们主要的区别在于须要建立对象的复杂程度上。
在抽象工厂模式中,抽象产品多是一个或多个,从而构成一个或多个产品族。在只有一个产品族的状况下,抽象工厂模式实际上退化到工厂方法模式。 java
java 代码
- // 产品 Plant接口
- public interface Plant {
- }
-
- // 具体产品PlantA,PlantB
- public class PlantA implements Plant {
-
- public PlantA() {
- System.out.println(" create PlantA ! ");
- }
-
- public void doSomething() {
- System.out.println(" PlantA do something ");
- }
- }
-
- public class PlantB implements Plant {
- public PlantB() {
- System.out.println(" create PlantB ! ");
- }
-
- public void doSomething() {
- System.out.println(" PlantB do something ");
- }
- }
-
- // 产品 Fruit接口
- public interface Fruit {
- }
-
- // 具体产品FruitA,FruitB
- public class FruitA implements Fruit {
- public FruitA() {
- System.out.println(" create FruitA ! ");
- }
-
- public void doSomething() {
- System.out.println(" FruitA do something ");
- }
- }
-
- public class FruitB implements Fruit {
- public FruitB() {
- System.out.println(" create FruitB ! ");
- }
-
- public void doSomething() {
- System.out.println(" FruitB do something ");
- }
- }
-
- // 抽象工厂方法
- public interface AbstractFactory {
- public Plant createPlant();
-
- public Fruit createFruit();
- }
-
- // 具体工厂方法
- public class FactoryA implements AbstractFactory {
- public Plant createPlant() {
- return new PlantA();
- }
-
- public Fruit createFruit() {
- return new FruitA();
- }
- }
-
- public class FactoryB implements AbstractFactory {
- public Plant createPlant() {
- return new PlantB();
- }
-
- public Fruit createFruit() {
- return new FruitB();
- }
- }
4. 小结 在如下状况下,应当考虑使用抽象工厂模式。 首先,一个系统应当不依赖于产品类实例被创立,组成,和表示的细节。这对于全部形态的工厂模式都是重要的。 其次,这个系统的产品有多于一个的产品族。 第三,同属于同一个产品族的产品是设计成在一块儿使用的。这一约束必须得在系统的设计中体现出来。 最后,不一样的产品以一系列的接口的面貌出现,从而使系统不依赖于接口实现的细节。 其中第二丶第三个条件是咱们选用抽象工厂模式而非其它形态的工厂模式的关键性条件。