Abstract Factory(抽象工厂)

2. Abstract Factory(抽象工厂)

2.1 定义

  为创建一组相关或相互依赖的对象提供一个接口,而且无须指定它们的具体类。抽象工厂模式是工厂方法模式的升级版本。在有多个业务品种、业务分类时,通过抽象工厂模式产生需要的对象是一种非常好的解决方式。

2.2 优点

  抽象工厂模式是工厂方法模式的升级版本。在有多个业务品种、业务分类时,通过抽象工厂模式产生需要的对象是一种非常好的解决方式。

2.2 缺点

  假如产品族中需要增加一个新的产品,不仅要实现具体的 产品类,而且还要创建相关的工厂接口。

2.3 c++源码示例

  1 #include<iostream>
  2 using namespace std;
  3 
  4 //抽象猫类
  5 class Cat{
  6 public:
  7     virtual string getType() = 0;
  8 };
  9 
 10 //白颜色猫
 11 class WhiteCat:public Cat{
 12 public:
 13     WhiteCat():Cat(),m_type("WhiteCat"){
 14 
 15     }
 16     string getType(){
 17         cout << m_type << endl;
 18         return m_type;
 19     }
 20 private:
 21     string m_type;
 22 };
 23 
 24 //黑色猫类
 25 class BlackCat:public Cat{
 26 public:
 27     BlackCat():Cat(),m_type("BlackCat"){
 28 
 29     }
 30     string getType(){
 31         cout << m_type << endl;
 32         return m_type;
 33     }
 34 private:
 35     string m_type;
 36 };
 37 
 38  //抽象狗类
 39 class Dog{
 40 public:
 41     virtual string getType() = 0;
 42 };
 43 
 44 //白色狗类
 45 class WhiteDog:public Dog{
 46 public:
 47     WhiteDog():Dog(),m_type("WhiteDog"){
 48 
 49     }
 50     string getType(){
 51         cout << m_type << endl;
 52         return m_type;
 53     }
 54 private:
 55     string m_type;
 56 };
 57 
 58 //黑色狗类
 59 class BlackDog:public Dog{
 60 public:
 61     BlackDog():Dog(),m_type("BlackDog"){
 62 
 63     }
 64     string getType(){
 65         cout << m_type << endl;
 66         return m_type;
 67     }
 68 private:
 69     string m_type;
 70 };
 71 
 72 //抽象工厂类
 73 class Pet
 74  {
 75  public:
 76      virtual  Cat* createCat() = 0;
 77      virtual  Dog* createDog() = 0;
 78  };
 79 
 80  //白色宠物工厂
 81 class WhitePetFactory
 82 {
 83 public:
 84      Cat* createCat(){
 85          return new WhiteCat();
 86      }
 87      Dog* creatDog(){
 88          return new WhiteDog();
 89      }
 90 };
 91  //黑色宠物工厂
 92  class BlackPetFactory
 93  {
 94  public:
 95      Cat* createCat(){
 96          return new BlackCat();
 97      }
 98      Dog* creatDog(){
 99          return new BlackDog();
100      }
101  };

 

posted @ 2020-11-03 09:49  昨日明眸  阅读(59)  评论(0)    收藏  举报