参考大话设计模式和网上的一些资料,自己编写下一些简单的设计模式,让自己了解这些设计模式的妙处!
#ifndef OPERATION_H #define OPERATION_H #include<iostream> using namespace std; class Operation { protected: double opA, opB; public: bool SetValue(double& n, double& m); virtual double GetResult()const=0; }; class OperationAdd :public Operation { double GetResult()const; }; class OperationSub :public Operation { double GetResult()const; }; class OperationMul :public Operation { double GetResult()const; }; class OperationDiv :public Operation { double GetResult()const; }; class OperationFactory { public: Operation * CreatOperation(char& operate); }; bool Operation::SetValue(double &n, double &m) { opA = n; opB = m; return true; } double OperationAdd::GetResult()const { double result; result = opA + opB; return result; } double OperationSub::GetResult()const { double result; result = opA - opB; return result; } double OperationMul::GetResult()const { double result; result = opA * opB; return result; } double OperationDiv::GetResult()const { if (opB == 0){ cout << "opB in OperationDiv can't be zero.\n"; return 0.00000001;} double result; result = opA / opB; return result; } Operation * OperationFactory::CreatOperation(char& operate) { Operation * Oper = NULL; switch (operate) { case('+') : Oper = new OperationAdd; break; case('-') : Oper = new OperationSub; break; case('*') : Oper = new OperationMul; break; case('/') : Oper = new OperationDiv; break; default: break; } return Oper; } #endif
#include"operation.h" int main() { double numA, numB; char op; Operation * Oper; OperationFactory OpFa; cout << "Please enter the numbers and operation(A op B)"; while (cin>>numA&&cin>>op&&cin>>numB){ Oper = OpFa.CreatOperation(op); Oper->SetValue(numA, numB); cout << "The result of " << numA << op << numB << "= " << Oper->GetResult() << endl; cout << "Please enter the numbers and operation(A op B)"; } return 0; }
时间: 2024-10-11 03:44:52