#include #include 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 ret = 0; return ret; }};//具体产品类class OperationAdd:public Operation{public: double getResult() { double ret = 0; ret = numberA + numberB; return ret; }};class OperationSub:public Operation{public: double getResult() { double ret = 0; ret = numberA - numberB; return ret; }};class OperationMul:public Operation{public: double getResult() { double ret = 0; ret = numberA * numberB; return ret; }};class OperationDiv:public Operation{public: double getResult() { double ret = 0; if(numberB != 0) ret = numberA / numberB; return ret; }};//工厂类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(int argc, char *argv[]){ Operation *oper = NULL; OperationFactory factory; oper = factory.CreateOperation('*'); oper->setA(1); oper->setB(3); cout<getResult()<
本文出自 “生命不息,奋斗不止” 博客,谢绝转载!