设计模式学习(原型模式)

原型模式是一种对象创建型模式, 它采取复制原型对象的方法来创建对象的实例。使用原型模式创建的实例,具有与原型一样的数据。
原型模式适用于一个复杂对象,具有自我复制功能,统一一套接口。


原型模式

#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
    virtual Person* Clone() = 0;
    virtual void printT() = 0;
};


class JavaProgrammer : public Person
{
public:
    JavaProgrammer()
    {
        this->m_age = 0;
        this->m_resume = NULL;
    }

    JavaProgrammer(string name, int age)
    {
        this->m_age = age;
        this->m_name = name;
        this->m_resume = NULL;
    }

    ~JavaProgrammer()
    {
        if (!m_resume)
        {
            delete m_resume;
            m_resume = NULL;
        }
    }

    Person* Clone()
    {
        JavaProgrammer *p = new JavaProgrammer;
        p->m_age = this->m_age;
        p->m_name = this->m_name;
        p->m_resume = NULL;
        if (this->m_resume)
        {
            //p->m_resume = new char[strlen(this->m_resume)];
            //strcpy(p->m_resume, this->m_resume);
        }
        return p;
    }

    void printT()
    {
        cout << "name: " << m_name << endl;
        cout << "age: " << m_age << endl;
        cout << "resume: " << &m_resume << endl;
    }

private:
    string m_name;
    int m_age;
    char *m_resume;
};


int main()
{
    Person *person = new JavaProgrammer("Bob", 26);
    Person *copy = person->Clone();
    person->printT();
    copy->printT();
    return 0;
}
相关文章
相关标签/搜索