Java设计模式之抽象工厂模式

一 、抽象工厂模式(Abstract Factory)
    抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

 

    抽象工厂(Abstract Factory)模式,又称工具箱(Kit 或Toolkit)模式。

 

二、创建过程如下

     一个具体工厂创建一个产品族一个产品族是不同系列产品的组合,产品的创建的逻辑分在在每个具体工厂类中。所有的具体工厂继承自同一个抽象工厂。
    客户端创建不同产品族的工厂,产品族的工厂创建具体的产品对客户端是不可见的。
    增加新的产品族时,需要增加具体工厂类,符合OCP原则。
    增加新产品时,需要修改具体工厂类和增加产品类,不符合OCP原则
    如果没有应对“多系列对象创建”的需求变化,则没有必要使用抽象工厂模式,这时候使用简单的静态工厂完全可以。

 

 

三、一个简单的实例

Java代码 复制代码
  1. // 产品 Plant接口   
  2. public interface IPlant { }   
  3. //具体产品PlantA,PlantB   
  4. public class PlantA implements IPlant {   
  5.   
  6.  public PlantA () {   
  7.   System.out.println("create PlantA !");   
  8.  }   
  9.   
  10.  public void doSomething() {   
  11.   System.out.println(" PlantA do something ...");   
  12.  }   
  13. }   
  14. public class PlantB implements IPlant {   
  15.  public PlantB () {   
  16.   System.out.println("create PlantB !");   
  17.  }   
  18.   
  19.  public void doSomething() {   
  20.   System.out.println(" PlantB do something ...");   
  21.  }   
  22. }   
  23. // 产品 Fruit接口   
  24. public interface IFruit { }   
  25. //具体产品FruitA,FruitB   
  26. public class FruitA implements IFruit {   
  27.  public FruitA() {   
  28.   System.out.println("create FruitA !");   
  29.  }   
  30.  public void doSomething() {   
  31.   System.out.println(" FruitA do something ...");   
  32.  }   
  33. }   
  34. public class FruitB implements IFruit {   
  35.  public FruitB() {   
  36.   System.out.println("create FruitB !");   
  37.  }   
  38.  public void doSomething() {   
  39.   System.out.println(" FruitB do something ...");   
  40.  }   
  41. }   
  42. // 抽象工厂方法   
  43. public interface AbstractFactory {   
  44.  public IPlant createPlant();   
  45.  public IFruit createFruit() ;   
  46. }   
  47. //具体工厂方法   
  48. public class FactoryA implements AbstractFactory {   
  49.  public IPlant createPlant() {   
  50.   return new PlantA();   
  51.  }   
  52.  public IFruit createFruit() {   
  53.   return new FruitA();   
  54.  }   
  55. }   
  56. public class FactoryB implements AbstractFactory {   
  57.  public IPlant createPlant() {   
  58.   return new PlantB();   
  59.  }   
  60.  public IFruit createFruit() {   
  61.   return new FruitB();   
  62.  }   
  63. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值