设计模式学习2 工厂模式
工厂模式其实就是简单模式的升级版本,
简单模式将界面与业务逻辑区分开,但是如果不停的增加计算器的运算方式,简单模式中的工厂Factory 中判断的业务逻辑会变非常复杂,这不符合封装的原则。
所以在此之上将Factory抽象了出来,代码如下:
class Cal { public: virtual double getResult() { return 0; } void setPara(double paraA,double paraB) { parameterA = paraA; parameterB = paraB; } protected: double parameterA; double parameterB; }; class Plus:public Cal { public: Plus(){} double getResult() { return parameterA + parameterB; } }; class Minus:public Cal { public: Minus(){} double getResult() { return parameterA - parameterB; } }; class FactoryInterface { public: virtual Cal * createCal() = 0; }; class AddFactory:public FactoryInterface { public: Cal *createCal() { return new Plus(); } }; class MinusFactory:public FactoryInterface { public: Cal *createCal() { return new Minus(); } }; void main() { double paraA = 5,paraB=43,result = 0; FactoryInterface *factory = new AddFactory; Cal *cal = factory->createCal(); cal->setPara(paraA,paraB); result = cal->getResult(); cout<<result<<endl; }