• 原型模式


    原型模式(Prototype)

    Definition:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。通俗来讲,从一个对象创建另外一个可定制的对象,不需要知道任何创建的细节。

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    /* Prototype abstract Class */
    class Prototype {
    public:
        virtual Prototype* clone() = 0;
        virtual void display() = 0;
    };
    
    /* 原型模式类的实现 */
    class Resume: public Prototype {
    public:
        Resume(string name, int id): m_name(name), m_id(id) {}
        Resume(const Resume &rm);
        void display();
        Prototype* clone();
    private:
        string m_name;
        int m_id;
    };
    
    //Important, copy construct function
    Resume::Resume(const Resume &rm) {
        this->m_id = rm.m_id;
        this->m_name = rm.m_name;
    }
    
    void Resume::display() {
        cout<<"my id is "<<this->m_id<<", my name is "<<this->m_name<<endl;
    }
    
    //Important, clone function
    Prototype* Resume::clone() {
        return new Resume(*this);
    }
    
    /* 测试 */
    void main() {
        Prototype* r1 = new Resume("zhao", 1);
        Prototype* r2 = r1->clone();
        Prototype* r3 = r2->clone();
    
        r1->display();
        r2->display();
        r3->display();
    
        delete r1;
        delete r2;
        delete r3;
    
        system("pause");
    }
    
    /* Result
    
    my id is 1, my name is zhao
    my id is 1, my name is zhao
    my id is 1, my name is zhao
    
    */

    Tips:

    支持复制(clone function)当前对象的模式.

    重要函数  拷贝构造函数和clone函数

  • 相关阅读:
    使用paramikoHelper类实现MySQL安装和数据恢复
    tornado-模板,转义,上传静态文件
    tornado-请求与响应
    tornado-输入
    tornado-输出,request
    配置Ubuntu虚拟环境
    tornado-简单的服务器非阻塞
    Linux查看进程,端口,访问url
    tornado-简单的服务器
    字符串,数组,定时器,form
  • 原文地址:https://www.cnblogs.com/hushpa/p/4432433.html
Copyright © 2020-2023  润新知