zoukankan      html  css  js  c++  java
  • 原型模式

    原型模式(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函数

  • 相关阅读:
    鼠标划过出现子菜单
    让dedecms(织梦)的list标签支持weight排序
    win7 64位无法安装网络打印机
    点击外部链接, 让iframe父页面也跟着显示
    C/C++指针(转)
    OO与设计模式的原则、目标 (转)
    页面添加QQ
    Windows Form 中的鼠标事件
    深入浅出C#消息
    初始化列表
  • 原文地址:https://www.cnblogs.com/hushpa/p/4432433.html
Copyright © 2011-2022 走看看