設計模式之工廠模式

2021-08-30 12:04:24 字數 2517 閱讀 4854

特徵:封裝物件的建立.

1,給乙個物件新增新型別時,類的建立必然要發生改變,導致了問題的出現.

2,解決辦法:強制用乙個通用的工廠(factory)來建立物件,而不允許將建立物件的**遍布於整個程式.

3,如果建立物件的**都裝到這個工廠執行,那麼在增加新物件時,所要做的全部工作就是只需修改工廠.

4,每個物件導向的應用程式都需要建立物件,並且因為人們可能新增新類來擴充套件應用程式,因此[b]工廠模式可能是所有設計模式中最有用的模式之一.[/b]

5,工程模式的實現方法之一:在基類中定義乙個靜態成員函式.

例項**:

#include

#include

#include

using namespace std;

class shape

class shape_error : public logic_error;};

static shape* factory(const string& type) throw(shape_error);

};class circle : public shape

//建構函式設為私有,保證只有靜態工廠方法可以建立物件

friend shape* shape::factory(const string& type);

public:

void draw() catch(shape::shape_error& e)

for(size_t i = 0; i < shapes.size(); i++)

for(vector::iterator ite=shapes.begin();ite!=shapes.end();ite++)

delete *ite;

return 0;

}

6,多型工廠模式:工廠方法作為單獨的類中的虛函式出現.

例項**:

#include

#include

#include

#include

using namespace std;

class shape

};class shapefactory //類工廠

friend class shapefactoryinitializer;

//核心方法

class shape_error : public logic_error;};

static shape* createshape(const string& id) throw(shape_error)

};mapshapefactory::factories;

class circle : public shape

//建構函式設為私有,保證只有靜態工廠方法可以建立物件

friend class shapefactoryinitializer; //友元

//注意私有友元類的使用

class factory;

friend class factory;

class factory : public shapefactory

friend class shapefactoryinitializer; //友元

};public:

void draw()

};shapefactoryinitializer shapefactoryinitializer::si;

char* sl = ;

int main()

catch(shapefactory::shape_error& e)

for(size_t i = 0; i < shapes.size(); i++)

for(vector::iterator ite=shapes.begin();ite!=shapes.end();ite++)

delete *ite;

return 0;

}

7,抽象工廠模式:

使用若干工廠方法模式,每個工廠方法模式建立乙個不同型別的物件.

#include

using namespace std;

class obstacle

;class fire : public obstacle

};class gg : public player

};class gamefactory

;class ggandwater : public gamefactory

virtual obstacle* makeobstacle()

};class mmandfire : public gamefactory

virtual obstacle* makeobstacle()

};class creategame //綜合管理

void player()

~creategame()

};int main()

設計模式 設計模式之工廠模式

工廠方法模式 建立模式 使用場景?作用?形態?場景 大量類似的實體類 要建立的實體類都是同一本質的東西 披薩 有部分類似功能 準備 烘烤 切法 實現方式不一樣 準備的材料不同 烘烤時間不同 切法不同 將繁瑣複雜的建立類的過程聚集在一起,有序清晰 把具體例項化的過程從客戶 中抽離 作用 1 將建立物件...

c 設計模式 之 工廠模式之 工廠模式

1 uml類圖 實現和依賴關係 實現 sportfactory jeepfactory hatchbackfactory 實現 ifactory 介面 sportcar jeepcar hatchbackcar 實現 icar 介面 依賴 ifactory 依賴 icar sportfactory ...

設計模式 工廠模式之簡單工廠模式

定義 由乙個工廠物件 工廠類 來指定建立某乙個產品類的例項。使用場景 客戶端只需傳入指定的引數即可,工廠類負責建立的物件較少 因為指定了傳入的引數 介面類 本想用iphone命名的,見諒 public inte ce phone實現介面類 public class huaweiphone imple...