Prototype模式去掉Clone方法
意图:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
结构图:
Prototype的主要缺陷是每一个Prototype的子类都必须实现Clone操作,这很烦。
一般都这样实现:
Prototype* ConcretePrototype::Clone()
{
return new ConcretePrototype(*this);
}
{
return new ConcretePrototype(*this);
}
现在想去掉这个重复的操作,
结构图如下:
实现如下:
class PrototypeWrapper
{
public:
~PrototypeWrapper() {}
virtual Prototype* clone() = 0;
};
template <typename T>
class PrototypeWrapperImpl : public PrototypeWrapper
{
public:
PrototypeWrapperImpl()
{
_prototype = new T();
}
virtual Prototype* clone()
{
return new T(*_prototype);
}
private:
T* _prototype;
};
T* _prototype;
};
使用:
PrototypeWrapper* prototype = new PrototypeWrapperImpl<ConcretePrototype>();
Prototype* p = prototype->clone();
本文提出了一种改进的Prototype模式实现方案,旨在避免每个Prototype子类都必须实现Clone操作的问题。通过引入PrototypeWrapper基类和模板类PrototypeWrapperImpl,可以统一处理复制逻辑。
7311

被折叠的 条评论
为什么被折叠?



