实现设计模式:原型模式
来源:互联网 发布:江铠同打郑爽耳光知乎 编辑:程序博客网 时间:2024/05/17 01:14
原型模式是一种很简单的模式,它能在不知道对象确切类型,只有基类信息的情况下,正确复制对象。
以下实现了一个原型工厂,可以利用保存在工厂里的原型,克隆出新的对象。
#include <map>#include <boost/function.hpp>namespace dp{template<class Key, class T>class prototype_factory{public:template<class Derive>void insert(const Key& key, const Derive& obj){m_prototypes.insert(std::make_pair(key, prototype<Derive>(obj)));}void remove(const Key& key){prototype_map::const_iterator it=m_prototypes.find(key);if(it!=m_prototypes.end())m_prototypes.erase(key);}T* clone(const Key& key) const{prototype_map::const_iterator it=m_prototypes.find(key);if(it!=m_prototypes.end())return (it->second)();return NULL;}private:template<class Derive>struct prototype{prototype(const Derive& obj) : m_obj(obj) { }T* operator()() const{return new Derive(m_obj);}const Derive& m_obj;};template<class Derive>prototype<Derive> get_prototype(const Derive* p){return prototype<Derive>(p);}typedef std::map<Key, boost::function<T*()> > prototype_map;prototype_map m_prototypes;};}
原型工厂对克隆对象除了有复制构造函数外,没其他要求。使用方式很简单。像下面的例子,类A和B是类Base的派生类。
A a;B b;dp::prototype_factory<int, Base> factory;factory.insert(1, a);factory.insert(2, b);Base* p=factory.clone(2);delete p;
- 实现设计模式:原型模式
- 设计模式之原型模式,C++实现
- C++设计模式实现--原型模式
- C++设计模式实现--原型模式
- 设计模式C++实现六: 原型模式
- scala实现设计模式之原型模式
- 大话设计模式c++实现--原型模式
- 设计模式----原型模式(C++实现)
- 设计模式---原型模式(C++实现)
- 设计模式:原型模式
- 设计模式------原型模式
- 设计模式 原型模式
- 设计模式-【原型模式】
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式-原型模式
- 设计模式- 原型模式
- 用Execute操作数据库
- linux下SVN配置笔记
- iBatis 到 MyBatis区别
- sql语句删除重复的记录的方法
- python django 表单
- 实现设计模式:原型模式
- 在Ring0下HOOK Ntdll.dll的Nt*函数的方法
- 关于重载的问题
- ACM算法训练
- MSSQL,Oracle 中,对应的RPAD,LPAD的功能函数进行字符补充
- js setTimeout 常见问题
- 英特尔对手机的几个痛苦领悟
- 设计模式之访问者模式(Vistor)
- iOS 30多个iOS常用动画,带详细注释