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

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

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. 小结
在以下情况下,应当考虑使用抽象工厂模式。
  首先,一个系统应当不依赖于产品类实例被创立,组成,和表示的细节。这对于所有形态的工厂模式都是重要的。
  其次,这个系统的产品有多于一个的产品族。
  第三,同属于同一个产品族的产品是设计成在一起使用的。这一约束必须得在系统的设计中体现出来。
  最后,不同的产品以一系列的接口的面貌出现,从而使系统不依赖于接口实现的细节。
  其中第二丶第三个条件是我们选用抽象工厂模式而非其它形态的工厂模式的关键性条件。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值