概念:簡單工廠模式即,只需要輸入實例化對象的名稱,工廠類就可以實例化出來需要的類。
核心:實現工廠模式的核心就是多個派生類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;
}
};
注:利用輸入的不同,實例化不同的類對象,同時這些類有事通過繼承基類的,那麼從而在基類的指針來調用基類的虛函數,從而達到調用不同的派生類的目的。