《Modern C++ Design》Policies 和Policy Classes
来源:互联网 发布:win10怎么打开网络共享 编辑:程序博客网 时间:2024/05/16 18:23
policy
所谓policy,其实就是一个类或者类模板的接口,它由内部类型定义(inner type definition),成员函数,成员变量组成。
它类似于设计模式中的Strategy.
这里先介绍一下Strategy:
结构 | |
意图 | 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。 |
适用性 |
|
下面举个例子,定义一个policy来生成实体:Creatorpolicy是个带有类型T的类模板,它提供一个Create的接口函数,此函数不接受参数,返回一个指向T的指针。每当Create被调用就返回一个指针。
下面是三个具体的实体。
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_;
};
这三个具体的实体就叫做policy classes或许有点不恰当,因为他们也带有模板。
policies接口和普通的类接口的区别在于它比较松散,没有类接口那样严格的限制,比如Create函数,我可以不必是virtual的,也可以不返回指针T,只需要必须定义Create就可以了。
前三个实例它们全都定义Create()並帶有必要的返回类型,所以它们都符合Creator policy。
现在设计一个使用Creatorpolicy的类,它用继承或复合的方式使用前面的第一个实例。
template <class CreationPolicy>
class WidgetManager : public CreationPolicy
{ ... };
如果这个类使用了一个或多个policies,我们称其为host或host classes,WidgetManager便是采用一个policies的host class. host 负责把polices提供的结构和行为组合成一个更复杂的结构和行为
当客户端将WidgetManager template具体化时,必须传进一个它所期望的policy
typedef WidgetManager< OpNewCreator<Widget> > MyWidgetMgr;
当MyWidgetMgr实体需要产生一个Widget实体时,它便调用它的policy子实体OpNewCreator<Widget>所提供的Create().选择生成策略(Create policy)是WidgetManage使用者自由。通过这样的设计,WidgetManager使用者便可自动装配他所要的功能。
《Modern C++ Design》Policies 和Policy Classes
- 《Modern C++ Design》Policies 和Policy Classes
- Generic design | Policies 和Policy Classes
- Policies 和 Policy Classes概念
- Modern C++ Design 学习笔记之Policy Based Class Design
- 关于Policy Based Class Design--《Modern C++ Design》读后感一
- [GP][Modern C++ Design]Policy-Based Class Design
- Modern C++ Design 笔记 第一章 Policy-Based Class Design
- Modern C++ Design 学习笔记之Policy Based Class Design
- Modern C++ Design 第一章 Policy-Based Class Design
- Reading Notes: Chapter 1. Policy-Based Class Design(Modern C++ Design By Andrei Alexandrescu)
- [C++] Modern C++ Design(MCD)学习笔记 && 测试代码
- Modern C++ Design, Spring Framework和Ruby的Mixin....
- Modern C++ Design, Spring Framework和Ruby的Mixin....
- Modern C++ Design
- Modern c++ design
- Modern c++ design 总结
- Modern C++ Design
- 《Modern C++ Design》摘要
- 游戏结束?中国游戏业界十大致命硬伤!
- makefie学习----引言
- 学习生活小结 -- W70 D6-D7
- 视频信号的数字化
- 防范网络攻击
- 《Modern C++ Design》Policies 和Policy Classes
- 利用javascript,根据confirm选择动态跳转页面
- 今天玩了一款游戏,很不错................
- 学习生活小结 -- W71 D1
- 实习感受--项目体会
- 百度2008笔试题(主要是Web前端)
- 安装 Windows xp 与 Linux 双操作系统
- CString 内存分配机制
- 通过SELECT语句自动得到SQL SERVER分页语句和查询总条数语句!