C++编程中使用设计模式中的policy策略模式的实例讲解
实例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 class class 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 code typedef WidgetManager<OpNewCreator> MyWidgetMgr; } 对于上面一个策略有3中不同的实现,从而就可以满足不同的客户的需求。 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); } };
总的说来策略模式: 缺点: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |