Prototype模式去掉Clone方法
 
意图:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
 
结构图:
 
 
                                   

Prototype的主要缺陷是每一个Prototype的子类都必须实现Clone操作,这很烦。
一般都这样实现:
 
Prototype* ConcretePrototype::Clone()
{
     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;
};
 
使用:
 

PrototypeWrapper* prototype = new PrototypeWrapperImpl<ConcretePrototype>();

Prototype* p = prototype->clone();

相关文章:

  • 2021-10-15
  • 2021-08-11
  • 2021-08-30
  • 2021-10-29
  • 2021-08-13
猜你喜欢
  • 2021-06-15
  • 2021-06-29
  • 2022-12-23
  • 2021-12-24
  • 2022-02-28
  • 2021-06-05
  • 2022-12-23
相关资源
相似解决方案