實例化對象的時候不再使用 new Object()形式,可以根據用戶的選擇條件來實例化相關的類。對於客戶端來說,去除了具體的類的依賴。只需要給出具體實例的描述給工廠,工廠就會自動返回具體的實例對象。
場景:採用簡單工廠模式設計一款運算器可以自由添加運算規則
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
/**
* 計算器運算抽象類
*/
class Operation {
private:
double numberA;//操作數A
double numberB;//操作數B
public:
/**
* 抽象方法
* 獲得操作結果
*/
virtual double getResult() = 0;
/**
* 獲取 操作數A
*/
double getNumberA() {
return this->numberA;
}
/**
* 設置 操作數A
*/
void setNumberA(double numberA) {
this->numberA = numberA;
}
/**
* 獲取 操作數B
*/
double getNumberB() {
return this->numberB;
}
/**
* 設置 操作數B
*/
void setNumberB(double numberB) {
this->numberB = numberB;
}
};
/**
* 加法運算類
*/
class OperationAdd: public Operation {
public:
double getResult() {
return getNumberA() + getNumberB();
}
};
/**
* 減法運算類
*/
class OperationSub: public Operation {
double getResult() {
return getNumberA() - getNumberB();
}
};
/**
* 乘法運算類
*/
class OperationMul: public Operation {
double getResult() {
return getNumberA() * getNumberB();
}
};
/**
* 除法運算類
*/
class OperationDiv: public Operation {
double getResult() {
double num = getNumberB();
if(num == 0)
throw "Division by zero condition!";
return getNumberA() / getNumberB();
}
};
/**
* 運算靜態工廠類
*/
class OperationFactory {
/**
* 創建運算工廠
* @param operate 操作符(+ - * /)
* @return 匹配運算類
*/
public:
Operation* createOperation(char c)
{
Operation *operation;
switch (c)
{
case '+':
operation=new OperationAdd();//創建加法運算類
break;
case '-':
operation=new OperationSub();//創建減法運算類
break;
case '*':
operation=new OperationMul();//創建乘法運算類
break;
case '/':
operation=new OperationDiv();//創建除法運算類
break;
}
return operation;
}
};
/**
* 大話設計模式(C++實現)
* 第一章:簡單工廠模式(靜態工廠模式)
*/
int main()
{
Operation *operation;
double result;
operation = OperationFactory().createOperation('+');
operation->setNumberA(1.1);
operation->setNumberB(2.2);
result = operation->getResult();
cout<<"加法結果:"<<result<<endl;
operation = OperationFactory().createOperation('-');
operation->setNumberA(3.3);
operation->setNumberB(2.2);
result = operation->getResult();
cout<<"減法結果:"<<result<<endl;
operation = OperationFactory().createOperation('*');
operation->setNumberA(3.3);
operation->setNumberB(2.2);
result = operation->getResult();
cout<<"乘法結果:"<<result<<endl;
operation = OperationFactory().createOperation('/');
operation->setNumberA(3.3);
operation->setNumberB(2.2);
result = operation->getResult();
cout<<"除法結果:"<<result<<endl;
return 0;
}
優點:我們可以對創建的對象進行一些 “加工” ,而且客戶端並不知道,因爲工廠隱藏了這些細節。如果,沒有工廠的話,那我們是不是就得自己在客戶端上寫這些代碼,這就好比本來可以在工廠裏生產的東西,拿來自己手工製作,不僅麻煩以後還不好維護。
缺點:如果需要在方法裏寫很多與對象創建有關的業務代碼,而且需要的創建的對象還不少的話,我們要在這個簡單工廠類裏編寫很多個方法,每個方法裏都得寫很多相應的業務代碼,而每次增加子類或者刪除子類對象的創建都需要打開這簡單工廠類來進行修改。這會導致這個簡單工廠類很龐大臃腫、耦合性高,而且增加、刪除某個子類對象的創建都需要打開簡單工廠類來進行修改代碼也違反了開-閉原則。