首页 > 代码库 > 设计模式1——抽象工厂

设计模式1——抽象工厂

抽象工厂通过一个工厂产生各种不同的实际对象,并返回基类的指针,通过基类的指针来统一对对象进行操作,增强了其灵活性,降低了耦合,便于后续更新和维护。

 

实例代码:

AbstractFactory.h内容

 1 #ifndef AbstractFactory_H_H 2 #define AbstractFactory_H_H 3  4 #include <iostream> 5 using namespace std; 6  7 class Oper 8 { 9 public:10     Oper(int a0, int b0) : a(a0), b(b0) {}11     virtual ~Oper() {}12     virtual int getResult() = 0;13 14 15 protected:16     int a, b;17 };18 19 class OperAdd : public Oper20 {21 public:22     OperAdd(int a0, int b0) : Oper(a0, b0) {}23     virtual int getResult(){24         return a+b;25     }26 };27 28 class OperSub : public Oper29 {30 public:31     OperSub(int a0, int b0) : Oper(a0, b0) {}32     virtual int getResult(){33         return a-b;34     }35 };36 37 class AbstractFactory38 {39 public:40     static Oper* create(int a0, int b0, char ch){41         Oper *oper = NULL;42         switch(ch){43         case +: oper = new OperAdd(a0, b0); break;44         case -: oper = new OperSub(a0, b0); break;45         }46         return oper;47     }48 };49 50 51 void AbstractFactoryTest()52 {53     int a = 4, b = 3;54     //Oper *oper = NULL;55     cout << AbstractFactory::create(a, b, +)->getResult() << endl;56     cout << AbstractFactory::create(a, b, -)->getResult() << endl;57 }58 59 60 #endif

具体运行在main函数中调用AbstractFactoryTest()即可。

设计模式1——抽象工厂