Design Pattern之工廠方法模式

2021-08-15 16:18:27 字數 2219 閱讀 8500

在本文之前,已經介紹過簡單工廠模式,簡單工廠模式只有乙個工廠,該工廠負責產生所有的運算類,如果增加乙個運算類,不僅需要修改工廠類,還需要修改客戶端類,這違反了設計模式所提倡的開放-封閉原則。本文所說的工廠方法模式就是在之前的簡單工廠模式前提下增加了各種運算方法的工廠類,uml圖如下:

相比較簡單工廠模式,只增加了運算子的工廠類,下面是**demo,運算子類這裡就不列舉,只給出工廠類以及客戶端**。

#ifndef  _operationfactory_h

#define _operationfactory_h

#include "operation.h"

//#define add 0x01

//#define sub 0x02

//#define mul 0x03

//#define div 0x04

class

operationfactory

~operationfactory() {}

virtual operation* createoperate( ) = 0;

};#endif // ! _operationfactory_h

//加法工廠

#ifndef __add_factory_h

#define __add_factory_h

#include "operationfactory.h"

#include "operationadd.h"

class addfactory: public operationfactory

~addfactory() {}

virtual operation* createoperate( )

};#endif // !__add_factory_h

//減法工廠

#ifndef __sub_factory_h

#define __sub_factory_h

#include "operationfactory.h"

#include "operationsub.h"

class subfactory : public operationfactory

~subfactory() {}

virtual operation* createoperate()

};#endif // !__sub_factory_h

//乘法工廠

#ifndef __mul_factory_h

#define __mul_factory_h

#include "operationfactory.h"

#include "operationmul.h"

class mulfactory : public operationfactory

~mulfactory() {}

virtual operation* createoperate()

};#endif // !__mul_factory_h

//除法工廠

#ifndef __div_factory_h

#define __div_factory_h

#include "operationfactory.h"

#include "operationdiv.h"

class divfactory : public operationfactory

~divfactory() {}

virtual operation* createoperate()

};#endif // !__div_factory_h

//客戶端**

#include "addfactory.h"

#include "subfactory.h"

#include "mulfactory.h"

#include "divfactory.h"

#include

#include

int _tmain(int argc, tchar* argv)

Design Pattern之策略模式

策略模式 strategy 它定義了演算法家族,分別封裝起來,讓它們之間可以互相替換,此模式讓演算法的變化,不會影響到使用演算法的客戶。策略模式就是用來封裝演算法的,實踐中,我們發現可以用它來封裝幾乎任何型別的規則,只要在分析過程中聽到需要在不同時間應用不同的業務規則,就可以考慮使用策略模式處理這種...

Design Pattern之模板方法模式

模板方法模式,定義乙個操作中的演算法的骨架,而將一些步驟延遲到子類中。模板方法使得子類可以不改變乙個演算法的結構即可重定義該演算法的某些特定步驟。abstractclass實現了乙個模板方法,定義了演算法的骨架,具體子類將重定義primitiveoperation以實現乙個演算法的步驟。concre...

Design Pattern之介面卡模式

介面卡模式將乙個類的介面轉換成客戶希望的另外乙個介面。adapter模式使得原本由於介面不相容而不能一起工作的那些類可以一起工作。在使用乙個已經存在的類時,如果它的介面,也就是方法和你的要求不同時,就應該考慮用介面卡模式。下面是介面卡的結構圖 如下 class player virtual play...