1. 抽象工厂模式能够说是简单工厂模式的扩展,它们主要的区别在于须要建立对象的复杂程度上。

1. 抽象工厂模式能够说是简单工厂模式的扩展,它们主要的区别在于须要建立对象的复杂程度上。
在抽象工厂模式中,抽象产品多是一个或多个,从而构成一个或多个产品族。在只有一个产品族的状况下,抽象工厂模式实际上退化到工厂方法模式。 java

java 代码
  1. //  产品 Plant接口         
  2. public interface Plant {   
  3. }   
  4.   
  5. // 具体产品PlantA,PlantB   
  6. public class PlantA implements Plant {   
  7.   
  8.     public PlantA() {   
  9.         System.out.println(" create PlantA ! ");   
  10.     }   
  11.   
  12.     public void doSomething() {   
  13.         System.out.println("  PlantA do something  ");   
  14.     }   
  15. }   
  16.   
  17. public class PlantB implements Plant {   
  18.     public PlantB() {   
  19.         System.out.println(" create PlantB ! ");   
  20.     }   
  21.   
  22.     public void doSomething() {   
  23.         System.out.println("  PlantB do something  ");   
  24.     }   
  25. }   
  26.   
  27. // 产品 Fruit接口   
  28. public interface Fruit {   
  29. }   
  30.   
  31. // 具体产品FruitA,FruitB   
  32. public class FruitA implements Fruit {   
  33.     public FruitA() {   
  34.         System.out.println(" create FruitA ! ");   
  35.     }   
  36.   
  37.     public void doSomething() {   
  38.         System.out.println("  FruitA do something  ");   
  39.     }   
  40. }   
  41.   
  42. public class FruitB implements Fruit {   
  43.     public FruitB() {   
  44.         System.out.println(" create FruitB ! ");   
  45.     }   
  46.   
  47.     public void doSomething() {   
  48.         System.out.println("  FruitB do something  ");   
  49.     }   
  50. }   
  51.   
  52. // 抽象工厂方法   
  53. public interface AbstractFactory {   
  54.     public Plant createPlant();   
  55.   
  56.     public Fruit createFruit();   
  57. }   
  58.   
  59. // 具体工厂方法   
  60. public class FactoryA implements AbstractFactory {   
  61.     public Plant createPlant() {   
  62.         return new PlantA();   
  63.     }   
  64.   
  65.     public Fruit createFruit() {   
  66.         return new FruitA();   
  67.     }   
  68. }   
  69.   
  70. public class FactoryB implements AbstractFactory {   
  71.     public Plant createPlant() {   
  72.         return new PlantB();   
  73.     }   
  74.   
  75.     public Fruit createFruit() {   
  76.         return new FruitB();   
  77.     }   
  78. }  
4. 小结 在如下状况下,应当考虑使用抽象工厂模式。   首先,一个系统应当不依赖于产品类实例被创立,组成,和表示的细节。这对于全部形态的工厂模式都是重要的。   其次,这个系统的产品有多于一个的产品族。   第三,同属于同一个产品族的产品是设计成在一块儿使用的。这一约束必须得在系统的设计中体现出来。   最后,不一样的产品以一系列的接口的面貌出现,从而使系统不依赖于接口实现的细节。   其中第二丶第三个条件是咱们选用抽象工厂模式而非其它形态的工厂模式的关键性条件。