2,抽象工厂模式(Abstract Factory Pattern) 抽象工厂可以一下生产一个产品族(里面有很多产品组成)

备注     工厂模式:要么生产香蕉、要么生产苹果、要么生产西红柿;但是不能同时生产一个产品组。

    抽象工厂:能同时生产一个产品族。===》抽象工厂存在原因

解释 :    具体工厂在开闭原则下,                能生产香蕉/苹果/梨子;  (产品等级结构)

              抽象工厂:在开闭原则下,               能生产:南方香蕉/苹果/梨子 (产品族)  北方香蕉/苹果/梨子

重要区别:

             工厂模式只能生产一个产品。(要么香蕉、要么苹果)

             抽象工厂可以一下生产一个产品族(里面有很多产品组成

  1 #include <iostre
  2 using namespace std;
  3 //水果虚父类 
  4 class Fruit
  5 {
  6 public:
  7     virtual void SayName() = 0;
  8 };
  9 //园区(多工厂)虚父类
 10 class AbstractFactory
 11 {
 12 public:
 13     virtual Fruit* CreateBanana() = 0;
 14     virtual Fruit* CreateApple() = 0;
 15 };
 16 //水果子类A 来自园区工厂
 17 class NorthBanana : public Fruit
 18 {
 19 public:
 20     virtual void SayName()
 21     {
 22         cout << "我是北方香蕉" << endl;
 23     }
 24 };
 25 //水果子类B 来自园区工厂
 26 class NorthApple : public Fruit
 27 {
 28 public:
 29     virtual void SayName()
 30     {
 31         cout << "我是北方苹果" << endl;
 32     }
 33 };
 34 
 35 //水果子类C 来自园区工厂
 36 class SourthBanana : public Fruit
 37 {
 38 public:
 39     virtual void SayName()
 40     {
 41         cout << "我是南方香蕉" << endl;
 42     }
 43 };
 44 
 45 //水果子类D 来自园区工厂
 46 class SourthApple : public Fruit
 47 {
 48 public:
 49     virtual void SayName()
 50     {
 51         cout << "我是南方苹果" << endl;
 52     }
 53 };
 54 //北方工厂 园区内
 55 class NorthFacorty : public AbstractFactory
 56 {
 57     virtual Fruit * CreateBanana()
 58     {
 59         return new NorthBanana;
 60     }
 61     virtual Fruit * CreateApple()
 62     {
 63         return new NorthApple;
 64     }
 65 };
 66 //南方工厂 园区内
 67 class SourthFacorty : public AbstractFactory
 68 {
 69     virtual Fruit * CreateBanana()
 70     {
 71         return new SourthBanana;
 72     }
 73     virtual Fruit * CreateApple()
 74     {
 75         return new SourthApple;
 76     }
 77 };
 78 
 79 
 80 void main()
 81 {
 82     Fruit            *fruit = NULL;
 83     AbstractFactory *af = NULL;
 84 
 85     ///---南方工厂 生产苹果 就是南方苹果  生产香蕉就是北方香蕉-----------
 86     af = new SourthFacorty;
 87     fruit = af->CreateApple();
 88     fruit->SayName();
 89     delete fruit;
 90     fruit = af->CreateBanana();
 91     fruit->SayName();
 92     delete fruit;
 93 
 94     ///------
 95     af = new NorthFacorty;
 96     fruit = af->CreateApple();
 97     fruit->SayName();
 98     delete fruit;
 99     fruit = af->CreateBanana();
100     fruit->SayName();
101     delete fruit;
102 
103     delete af;
104     system("pause");
105     return ;
106 }

 

posted @ 2017-08-10 01:22  杜东洲  阅读(521)  评论(0编辑  收藏  举报