在看《C++設計新思維》的時候,發現在一開始就大篇幅的介紹策略模式(policy),策略模式不屬于經典設計模式中的一種,但是其實在我們日常的開發中是必不可少的。policy,策略,方針,這里的意思是指把復雜功能的類盡量的拆分為功能單一的簡單類的組合,簡單的類只負責單純行為或結構的某一方面。增加程序庫的彈性,可復用性,可擴展性。policy是一個虛擬的概念,他定義了某一類class的一些接口規范,并不與C++語法的關鍵字對應,只是一個抽象的概念。
實例1:
//policy模式的常見使用實例smartptr,template< class T, template <class> class CheckingPolicy, template <class> class ThreadingModel>class SmartPtr : public CheckingPolicy<T> , public ThreadingModel<SmartPtr>{ T* operator->() { typename ThreadingModel<SmartPtr>::Lock guard(*this); CheckingPolicy<T>::Check(pointee_); return pointee_; }private: T* pointee_;};
實例2,比如說:我們定義一個policy,他是一個帶有參數T的一個模版,他必須有一個Create函數,且返回T類型指針。對于這個定義,我們可以有不同的實現,從而滿足不同用戶的不同的需求。
template <class T>struct OpNewCreator{ static T* Create() { return new T; }};template <class T>struct MallocCreator{ static T* Create() { void* buf = std::malloc(sizeof(T)); if (!buf) return 0; return new(buf) T; }};template <class T>struct PrototypeCreator{ PrototypeCreator(T* pObj = 0) :pPrototype_(pObj) {} T* Create() { return pPrototype_ ? pPrototype_->Clone() : 0; } T* GetPrototype() { return pPrototype_; } void SetPrototype(T* pObj) { pPrototype_ = pObj; }private: T* pPrototype_;};//test classclass Widget{};//調用方法一:template <class CreationPolicy>class WidgetManager : public CreationPolicy{ };void main(){typedef WidgetManager< OpNewCreator<Widget> > MyWidgetMgr;}//調用方法二:因為一般Manager是特定于某一類的class,所以在Manager中就指定要處理的class類型。template <template <class Created> class CreationPolicy>class WidgetManager : public CreationPolicy<Widget>{ };void main(){ // Application codetypedef WidgetManager<OpNewCreator> MyWidgetMgr;}
對于上面一個策略有3中不同的實現,從而就可以滿足不同的客戶的需求。
但是對于上面的使用,我們還可以有更好的修改:因為Policy的實現class一般會被繼承,所以我們要考慮他的析構,一般的我們使析構函數virtual,但是這里會影響template的靜態編譯特性,影響效率,所以我們使用protected或private的析構函數,既不影響繼承類對基類的析構,也不影響使用。
如修改如下:
template <class T>struct OpNewCreator{ static T* Create() { return new T; }protected: ~OpNewCreator() {}};
我們還可以修改上面的manger,實現creator policy的switch:
template <template <class> class CreationPolicy>class WidgetManager : public CreationPolicy<Widget>{ void SwitchPrototype(Widget* pNewPrototype) { CreationPolicy<Widget>& myPolicy = *this; delete myPolicy.GetPrototype(); myPolicy.SetPrototype(pNewPrototype); }};
policy 模式對我們創建可復用,可擴展的庫的開發有非常重要的作用,是OO的基本的設原則式之一。
總的說來策略模式:
優點:
1、 使用策略模式可以避免使用多重條件轉移語句。多重轉移語句不易維護。
2、 策略模式讓你可以動態的改變對象的行為,動態修改策略
缺點:
1、客戶端必須知道所有的策略類,并自行決定使用哪一個策略類。
2、類過多---策略模式造成很多的策略類,每個具體策略類都會產生一個新類。(這點可以通過享元模式來克服類過多)