设计模式(三)--抽象工厂模式

设计模式(三)--抽象工厂模式

 

抽象工厂模式的作用,可以处理具有相同等级结构的多个产品族中产品对象的创建问题。

首先解释一下产品族和相同等级结构的概念

相同等级结构:  抽象产品A和抽象产品B处于同一个继承等级(父类),因此成为具有相同等级结构。这里关键是要理解A和B都是相互独                         立的抽象产品,在JAVA中用接口定义。

产品族:具体产品A1和具体产品A2都是由抽象产品继承下来的产品,这两个子类成为父类的产品族

 
 

抽象工厂的类图如下

抽象工厂的源代码

  1. public interface Creator    
  2. {    
  3.     /**  
  4.      * A的抽象工厂方法 
  5.      */    
  6.     public ProductA factoryA();    
  7.     /**  
  8.      * B的抽象工厂方法 
  9.      */    
  10.     public ProductB factoryB();    
  11. }    

具体工厂1的源码

  1. public class ConcreteCreator1 implements Creator    
  2. {    
  3.     /**  
  4.      * A的具体工厂  
  5.      */    
  6.     public ProductA factoryA()    
  7.     {    
  8.         return new ProductA1();    
  9.     }    
  10.     /**  
  11.      * B的具体工厂  
  12.      */    
  13.     public ProductB factoryB()    
  14.     {    
  15.         return new ProductB1();    
  16.     }    
  17. }   

具体工厂2的源码

  1. public class ConcreteCreator2 implements Creator    
  2. {    
  3.     /**  
  4.      * A的具体工厂  
  5.      */    
  6.     public ProductA factoryA()    
  7.     {    
  8.         return new ProductA2();    
  9.     }    
  10.     /**  
  11.      * B的具体工厂  
  12.      */    
  13.     public ProductB factoryB()    
  14.     {    
  15.         return new ProductB2();    
  16.     }    
  17. }   

抽象产品A源码

  1. public interface ProductA    
  2. {    
  3. }    

抽象产品B源码

  1. public interface ProductB    
  2. {    
  3. }    

具体产品A1源码

  1. public class ProductA1 implements ProductA    
  2. {    
  3.     public ProductA1()    
  4.     {    
  5.         //do something    
  6.     }    
  7. }    

具体产品A2源码

  1. public class ProductA2 implements ProductA    
  2. {    
  3.     public ProductA2()    
  4.     {    
  5.         //do something    
  6.     }    
  7. }    

具体产品B1源码

  1. public class ProductB1 implements ProductB    
  2. {    
  3.     public ProductB1()    
  4.     {    
  5.         //do something    
  6.     }    
  7. }    

具体产品B2源码

  1. public class ProductB2 implements ProductB    
  2. {    
  3.     public ProductB2()    
  4.     {    
  5.         //do something    
  6.     }    
  7. }    
魔由心生,有万境纵横,无一道清静,无量寿佛!
原文地址:https://www.cnblogs.com/qihuan/p/3954075.html