实现设计模式:原型模式

原型模式是一种很简单的模式,它能在不知道对象确切类型,只有基类信息的情况下,正确复制对象。

以下实现了一个原型工厂,可以利用保存在工厂里的原型,克隆出新的对象。

#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;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值