栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++编程中使用设计模式中的policy策略模式的实例讲解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++编程中使用设计模式中的policy策略模式的实例讲解


   在看《C++设计新思维》的时候,发现在一开始就大篇幅的介绍策略模式(policy),策略模式不属于经典设计模式中的一种,但是其实在我们日常的开发中是必不可少的。policy,策略,方针,这里的意思是指把复杂功能的类尽量的拆分为功能单一的简单类的组合,简单的类只负责单纯行为或结构的某一方面。增加程序库的弹性,可复用性,可扩展性。policy是一个虚拟的概念,他定义了某一类class的一些接口规范,并不与C++语法的关键字对应,只是一个抽象的概念。

实例1:

//policy模式的常见使用实例smartptr,
template
<
  class T,
  template  class CheckingPolicy,
  template  class ThreadingModel
>
class SmartPtr
  : public CheckingPolicy
  , public ThreadingModel
{  
  T* operator->()
  {
   typename ThreadingModel::Lock guard(*this);
   CheckingPolicy::Check(pointee_);
   return pointee_;
  }
private:
  T* pointee_;
};

实例2,比如说:我们定义一个policy,他是一个带有参数T的一个模版,他必须有一个Create函数,且返回T类型指针。对于这个定义,我们可以有不同的实现,从而满足不同用户的不同的需求。

template 
struct OpNewCreator
{
  static T* Create()
  {
   return new T;
  }
};

template 
struct MallocCreator
{
  static T* Create()
  {
   void* buf = std::malloc(sizeof(T));
   if (!buf) return 0;
   return new(buf) T;
  }
};

template 
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 WidgetManager : public CreationPolicy
{  
};
void main()
{

typedef WidgetManager< OpNewCreator > MyWidgetMgr;


}

//调用方法二:因为一般Manager是特定于某一类的class,所以在Manager中就指定要处理的class类型。
template