原型模式是一种很简单的模式,它能在不知道对象确切类型,只有基类信息的情况下,正确复制对象。
以下实现了一个原型工厂,可以利用保存在工厂里的原型,克隆出新的对象。
#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;