首页 > 代码库 > 大话设计模式C++实现一:简单工厂模式
大话设计模式C++实现一:简单工厂模式
#include <iostream> #include <cstdlib> 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; 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; double A; double B; char op; cout << "Input A:"; cin >> A; cout << "Input B:"; cin >> B; cout << "Input oper:"; cin >> op; oper = of.createOperation(op); oper->setA(A); oper->setB(B); cout << oper->GetResult() << endl; if (oper != NULL) { delete oper; oper = NULL; } return 0; }
大话设计模式C++实现一:简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。