标签:
由于面向过程编程造成的代码膨胀问题越来越严重,使其维护的代价高,灵活性很低。为了使代码易维护、易扩展、易复用和灵活性好,所以我们在采用面向对象编程的时候,防止采用面向对象的语言实际上却做着面向过程的事儿,更需要采用某种设计模式,核心就是使程序变得高内聚,低耦合,这样的程序才能达到上面的四个优点。而简单工厂模式的出现也正是为了达到这样一种效果,将工厂和产品分块,具体解决了实例化那个对象(具体产品)的需求。从而实现了高内聚,低耦合。使程序易维护、易扩展、易复用和灵活性好。同时也用到了面向对象编程的三大特性:继承、多态、封装。#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 OperationFactory { public: Operation* createOperation(char type) { Operation* oper; switch(type) { case '+': oper=new OperationAdd; break; case '-': oper=new OperationSub; break; case '*': oper=new OperationMul; break; case '/': oper=new OperationDiv; break; } return oper; } }; //客户端 int main() { Operation* oper=NULL; OperationFactory of; oper=of.createOperation('+'); oper->setA(3); oper->setB(2); cout<<oper->GetResult()<<endl; if(oper!=NULL) { delete oper; oper=NULL; } system("pause"); return 0; }
运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51924764