標籤:c++ 物件導向 開發模式 Factory 方法模式
Factory 方法模式(Factory Method):定義一個用於封建對象的介面,讓子類覺得史麗華哪一個類,Factory 方法使一個類的執行個體化延遲到其子類。
簡單原廠模式優點 :工廠類中包含了必要的邏輯判斷,根據用戶端的選擇條件動態執行個體化相關的類,對於用戶端來說,去除了與具體產品的依賴。但是因為我們需要根據用戶端的輸入來修執行個體化類,如果我們要增加類的話,我們需要修改工廠類方法,把該類加入其中,這意味著我們不但對擴充開發了,對修改也開發了,違背了開放-封閉原則。這就可以用Factory 方法來解決這個問題。
Factory 方法模式實現時,用戶端需要決定執行個體化哪一個工廠來實現運算類,選擇判斷的問題還是存在的,也就是說,Factory 方法把簡單工廠的內部邏輯判斷移到了用戶端代碼來進行,你想要增加功能,本來是改工廠類的,而現在是修改用戶端。
<pre name="code" class="cpp">#ifndef FACTORY_MEANS_H#define FACTORY_MEANS_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 IFactory{public:virtual Operation *CreatOperation()=0;}; class AddFactory : public IFactory{public:Operation *CreatOperation(){return new OperationAdd();}};class SubFactory : public IFactory{public:Operation *CreatOperation(){return new OperationSub();}};class MulFactory : public IFactory{public:Operation *CreatOperation(){return new OperationMul();}};class DivFactory : public IFactory{public:Operation *CreatOperation(){return new OperationDiv();}};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;}#endif
#include"FactoryMeans.h"int main(){IFactory *operA = new AddFactory;Operation *opera = operA->CreatOperation();IFactory *operS = new SubFactory;Operation *opers = operS->CreatOperation();IFactory *operM = new MulFactory;Operation *operm = operM->CreatOperation();IFactory *operD = new DivFactory;Operation *operd = operD->CreatOperation();double a, b;while (cin >> a&&cin >> b){opera->SetValue(a,b );cout << "the result of " << a << " add " << b << " equal " << opera->GetResult() << endl;opers->SetValue(a, b);cout << "the result of " << a << " sub " << b << " equal " << opers->GetResult() << endl;operm->SetValue(a, b);cout << "the result of " << a << " mul " << b << " equal " << operm->GetResult() << endl;operd->SetValue(a, b);cout << "the result of " << a << " div " << b << " equal " << operd->GetResult() << endl;}return 0;}
設計模式C++實現五:Factory 方法模式