【Linux】設計模式-----簡單工廠模式
阿新 • • 發佈:2019-01-09
概念:簡單工廠模式即,只需要輸入例項化物件的名稱,工廠類就可以例項化出來需要的類。
核心:實現工廠模式的核心就是多個派生類public繼承基類,同時根據使用者的需求在簡單工廠類裡面例項化基類的物件,從而根據基類裡面的虛擬函式來實現對派生類的函式呼叫,同時實現多型。
如圖:
利用簡單計算器的例項來實現工廠模式:
#include<iostream>
using namespace std;
class _operator{
private:
int a;
int b;
public:
void setA(int _a) {a = _a;}
void setB(int _b) {b = _b;}
int GetA() {return a;}
int GetB() {return b;}
virtual int result() {return 0;}// 虛擬函式,為了通過基類的指標來呼叫派生類的物件
};
//通過對基類的虛擬函式進行不同的重寫,在呼叫的時候可以根據不同的需求進行不同的例項化
class Add:public _operator{
int result() {return GetA() + GetB();}
};
class Sub:public _operator{
int result() {return GetA() - GetB();}
};
class Mul:public _operator{
int result() {return GetA() * GetB();}
};
class Div:public _operator{
int result() {return GetA() / GetB();}
};
class factory{
public:
static _operator* GetOperator(char ch){
_operator* p = NULL;
switch(ch){
case '+':
p = new Add();
break;
case '-':
p = new Sub();
break;
case '*':
p = new Mul();
break;
case '/':
p = new Div();
break;
default:
exit(1);
}
return p;
}
};
注:利用輸入的不同,例項化不同的類物件,同時這些類有事通過繼承基類的,那麼從而在基類的指標來呼叫基類的虛擬函式,從而達到呼叫不同的派生類的目的。