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;
    }
  • 相关阅读:
    94. Binary Tree Inorder Traversal
    101. Symmetric Tree
    38. Count and Say
    28. Implement strStr()
    实训团队心得(1)
    探索性测试入门
    LC.278. First Bad Version
    Search in Unknown Sized Sorted Array
    LC.88. Merge Sorted Array
    LC.283.Move Zeroes
  • 原文地址:https://www.cnblogs.com/venow/p/2755913.html
Copyright © 2011-2022 走看看