zoukankan      html  css  js  c++  java
  • 小话设计模式六:原型模式

    原型模式定义:

      用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

    原型模式解析:

      原型模式是一种创建型设计模式,该模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。它主要面对的问题为:"某些结构复杂的对象"的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。

      UML图如下:

      简单示例代码如下:

    //基类
    class Prototype
    {
    public:
        virtual ~Prototype();
        virtual Prototype* Clone() const = 0; //一个克隆自身的虚函数,调用拷贝构造函数
    protected:
        Prototype();
    };
    
    Prototype::Prototype()
    {
        cout<<"Construct Prototype"<<endl;
    }
    
    Prototype::~Prototype()
    {
        cout<<"Destruct Prototype"<<endl;
    }
    
    class ConcretePrototype : public Prototype
    {
    public:
        ConcretePrototype();
        ConcretePrototype(const ConcretePrototype& rhs);
        ~ConcretePrototype();
        virtual Prototype* Clone() const;
    };
    
    ConcretePrototype::ConcretePrototype()
    {
        cout<<"Construct ConcretePrototype"<<endl;
    }
    
    ConcretePrototype::ConcretePrototype(const ConcretePrototype& rhs)
    {
        cout<<"Copy Construct ConcretePrototype"<<endl;
    }
    
    ConcretePrototype::~ConcretePrototype()
    {
        cout<<"Destruct ConcretePrototype"<<endl;
    }
    
    Prototype* ConcretePrototype::Clone() const
    {
        return new ConcretePrototype(*this);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        Prototype* pInstanceOne = new ConcretePrototype;
        Prototype* pInstanceTwo = pInstanceOne->Clone();
    
        delete pInstanceOne;
        delete pInstanceTwo;
        return 0;
    }
  • 相关阅读:
    margin:0 auto; 为什么会失效
    vue 登录滑块验证
    layui table 添加序号列
    纯css :after 菜单后面添加“<”
    设置div为不可点击
    ubuntu中root用户在图形界面登录
    ubuntu root用户无法登录filezilla的问题
    ubuntu无法用putty登录
    解决ubuntu和windows电脑之间无法复制粘贴问题
    E: Unable to locate package ubuntu
  • 原文地址:https://www.cnblogs.com/venow/p/2755913.html
Copyright © 2011-2022 走看看