設計模式C++實現一:簡單工程模式

來源:互聯網
上載者:User

標籤:c++   物件導向   設計模式   簡單原廠模式   

參考大話設計模式和網上的一些資料,自己編寫下一些簡單的設計模式,讓自己瞭解這些設計模式的妙處!


#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;}


設計模式C++實現一:簡單工程模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.