include <iostream> class operation { public: operation() : num_left(0), num_right(0) {} virtual void GetResult(); void setnum(double l,double r) { num_left=l; num_right=r; } ~operation() {} public: double num_left; double num_right; }; class operationAdd : public operation { public: operationAdd() {} virtual void GetResult(); }; class operationSub : public operation { public: operationSub() {} virtual void GetResult(); }; class operationMul : public operation { public: operationMul() {} virtual void GetResult(); }; class operationDiv : public operation { public: operationDiv() {} virtual void GetResult(); }; class operationFactory { public: static operation* createOperation(char operate); ~operationFactory(); };
//main.cpp #include "Factory.h" void operation::GetResult() { } void operationAdd::GetResult() { double result=num_left+num_right; std::cout<<num_left<<"+"<<num_right<<"="<<result<<std::endl; } void operationSub::GetResult() { double result=num_left-num_right; std::cout<<num_left<<"-"<<num_right<<"="<<result<<std::endl; } void operationMul::GetResult() { double result=num_left*num_right; std::cout<<num_left<<"*"<<num_right<<"="<<result<<std::endl; } void operationDiv::GetResult() { double result=0; if (num_right==0) { std::cout<<"除数不能为0.../n"; return ; } else { result=num_left/num_right; std::cout<<num_left<<"/"<<num_right<<"="<<result<<std::endl; } } operation* operationFactory::createOperation(char operate) { operation *oper; switch (operate) { case '+': oper=new operationAdd(); break; case '-': oper=new operationSub(); break; case '*': oper=new operationMul(); break; case '/': oper=new operationDiv(); break; } return oper; } int main() { loop: std::cout<<"请输入左操作数:"; double l(0); std::cin>>l; std::cout<<"请选择运算操作: 1-/'+/',2-/'-/',3-/'*/',4-/'//' /n你选择:"; char c; int choice(0); std::cin>>choice; switch (choice) { case 1: c='+';break; case 2: c='-';break; case 3: c='*';break; case 4: c='/';break; } std::cout<<"请输入右操作数:"; double r(0); std::cin>>r; operation *oper=operationFactory::createOperation(c); oper->setnum(l,r); oper->GetResult(); delete oper; std::cout<<"还需要继续运算吗?(Y/N):"; char yes_no; std::cin>>yes_no; if (yes_no=='Y'|| yes_no== 'y') { goto loop; } return 0; }
心得:工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,工厂模式也就是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑实用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。
