标签:
有了前面介绍的简单工厂模式,为什么又会出来一个工厂模式呢?它们之间的区别又在哪里?工厂模式的精髓又在哪里?具体实现代码:
#include <iostream> using namespace std; //抽象产品类 class Operation { protected: double numberA; double numberB; public: double getA() { return numberA; } double getB() { return numberB; } void setA(double number) { numberA=number; } void setB(double number) { numberB=number; } virtual double GetResult() { double result=0; return result; } }; //下面是四个具体产品类,只能是同一类的产品; class OperationAdd:public Operation { public: double GetResult() { double result=0; result=numberA+numberB; return result; } }; class OperationSub:public Operation { public: double GetResult() { double result=0; result=numberA-numberB; return result; } }; class OperationMul:public Operation { public: double GetResult() { double result=0; result=numberA*numberB; return result; } }; class OperationDiv:public Operation { public: double GetResult() { double result=0; if(numberB!=0) result=numberA/numberB; return result; } }; //抽象工厂类 class AbstractFactory { public: virtual Operation* createOperation() { return new Operation; } }; //下面是四个具体工厂类,分别用于产生四个具体产品 class AddFactory:public AbstractFactory { public: Operation* createOperation() { Operation* oper=new OperationAdd; return oper; } }; class SubFactory:public AbstractFactory { public: Operation* createOperation() { Operation* oper=new OperationSub; return oper; } }; class MulFactory:public AbstractFactory { public: Operation* createOperation() { Operation* oper=new OperationMul; return oper; } }; class DivFactory:public AbstractFactory { public: Operation* createOperation() { Operation* oper=new OperationDiv; return oper; } }; //客户端 int main() { //客户端判断具体实例化那个子工厂,那个具体产品; AbstractFactory* af=NULL; af=new AddFactory(); Operation* oper=NULL; oper=af->createOperation(); oper->setA(3); oper->setB(2); cout<<oper->GetResult()<<endl; if(af!=NULL) { delete af; af=NULL; } if(oper!=NULL) { delete oper; oper=NULL; } system("pause"); return 0; }运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51925082