大話設計模式中簡單原廠模式的計算機執行個體的C++代碼

來源:互聯網
上載者:User

這裡只是實現了加減乘除,和書中的C#實現的方法基本相似。

#include <iostream>#include <string>using namespace std;//Operation運算類class Operation{private:double _numberA;double _numberB;public:Operation(){}Operation(double numA,double numb):_numberA(numA),_numberB(numb){}virtual double GetResult(){double result = 0;return result;}void set_numberA(double numA){_numberA = numA;}void set_numberB(double numB){_numberB = numB;}double get_numberA(){return _numberA;}double get_numberB(){return _numberB;}};//加減乘除類class OperationAdd: public Operation{public:OperationAdd() { }OperationAdd(double numA,double numB):Operation(numA,numB){}double GetResult(){double result = 0;result = get_numberA()+get_numberB();return result;}};class OperationSub:public Operation{public:OperationSub() { }OperationSub(double numA,double numB):Operation(numA,numB){}double GetResult(){double result = 0;result = get_numberA()+get_numberB();return result;}};class OperationMul: public Operation{public:OperationMul() { }OperationMul(double numA,double numB):Operation(numA,numB){}double GetResult(){double result = 0;result = get_numberA()+get_numberB();return result;}};class OperationDiv:public Operation{public:OperationDiv() { }OperationDiv(double numA,double numB):Operation(numA,numB){}double GetResult(){double result = 0;if( get_numberB() == 0){throw new exception("除數不能為零");}result = get_numberA()+get_numberB();return result;}};//簡單運算工廠類class OperationFactory{public: Operation* createOperate(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(){Operation *oper;OperationFactory operFactory;oper = operFactory.createOperate('+');oper->set_numberA(1);oper->set_numberB(2);double result = oper->GetResult();cout<<"result = "<<result<<endl;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.