最近在學習設計模式,很多人說《大話設計模式》比較適合入門,就拿來看看。但是,書裡的**實現全是c#的,於是想用c++實現一遍。
簡單工廠模式**實現如下:
operation.h實現如下:
#pragma once
#include "operationlib.h"
#include using namespace std;
enum operatorenum
;class operationlib_api coperation
;class coperationadd: public coperation
;class coperationsub: public coperation
;class coperationmul: public coperation
;class coperationdiv: public coperation
;class coperationsqr: public coperation
;class coperationsqrt: public coperation
;class coperationreverse: public coperation;//
class operationlib_api coperationfactory
;
operation.cpp **如下:
#include "stdafx.h"
#include "operation.h"
double coperation::m_numbera = 0;
double coperation::m_numberb = 0;
coperation::coperation(void)
coperation::coperation(double numa, double numb)
coperation::~coperation(void)
double coperation::getresult()
double coperationadd::getresult()
double coperationsub::getresult()
double coperationmul::getresult()
double coperationdiv::getresult()
result = m_numbera / m_numberb;
return result;}//
operatorenum stringtoemun(std::string stroper)
else if (0 == stroper.compare("-"))
else if (0 == stroper.compare("*"))
else if (0 == stroper.compare("/"))
return unknow;
}coperation* coperationfactory::createoperation(std::string soper)
case sub:
case mul:
case div:
}return oper;
}
operationmain.cpp 實現如下:
//#include "stdafx.h"
#include #include #include "operation.h"
using namespace std;
int _tmain(int argc, _tchar* argv)
{ try
{ double numa, numb;
std::string stroper;
cout<<"請輸入數字a:";
cin>>numa;
cout<<"請選擇運算符號(+、-、*、/):";
cin>>stroper;
cout<<"請輸入數字b:";
cin>>numb;
coperation* oper = new coperation(numa, numb);
oper = coperationfactory::createoperation(stroper);
double result = oper->getresult();
cout<<"計算結果:"<
設計模式學習筆記一 簡單工廠模式
一 建立模式 建立模式分為類的建立模式和物件的建立模式兩種 1 類的建立模式 類的建立模式使用繼承關係,把類的建立延遲到子類,從而封裝了客戶端將得到哪些具體類的資訊,並且隱藏了這些類的例項是如何被建立和放在一起的。2 物件的建立模式 而物件的建立模式則把物件的建立過程動態地委派給另乙個物件,從而動態...
設計模式學習筆記(一) 簡單工廠
大話設計模式 學習筆記,參考鏈結 伍迷的小菜程式設計成長記 1 2 pragma once34 操作類 5class operation 6 11 int getnumberb void 12void setnumbera int numbera 13void setnumberb int numb...
C 設計模式學習筆記(一) 之 簡單工廠模式
這是乙個關於記錄我學習 c 設計模式的系列筆記,主要是記錄一些知識點,和一些個人的理解。如果真能幫助到大家的話,哪怕是一點點,我也是很開心的啦。ps 由於本人第一次寫部落格,所以我寫得可能會很亂,有什麼建議和不足的還請大家幫幫我。我個人認為蛤,學什麼東西嘛,要做到以下幾個點 我們為什麼要去學它,學它...