原型模式

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

一般在初始化的信息不发生变化的情况下,克隆是最好的办法.这即隐藏了对象创建的细节,又对性能是大大的提高,它等于是不用重新初始化对象,而是动态地获得对象运行时的状态

浅复制:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用都仍然指向原来的对象

深复制:把引用对象的变量指向复制过的新对象,而不是原有的被引用的对象,把复制对象所引用的对象都复制一遍

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

class MailReceiver
{
public:
    MailReceiver(int gender,const char* name)
    {
        mGender = gender;
        strcpy(mName,name);
    }
    ~MailReceiver(){}
public:
    int mGender;//0:female 1:male
    char mName[128];
};

class Mail
{
public:
    Mail()
    {
        bzero(mContent,sizeof(mContent));
        mMailReceiver = new MailReceiver(0,"unknown");
    }
    Mail(Mail* mail)
    {
        strcpy(mContent,mail->mContent);
        mMailReceiver = new MailReceiver(0,"unknown");
    }
    ~Mail(){}

    void setContent(const char* content)
    {
        strcpy(mContent,content);
    }

    void showContent()
    {
        if(mMailReceiver->mGender==0){
            cout << mContent << ",Mrs " << mMailReceiver->mName << endl;
        }else{
            cout << mContent << ",Mr " << mMailReceiver->mName << endl;
        }
    }
    Mail* clone()
    {
        return new Mail(this);
    }
    void setReceiver(MailReceiver* mailReceiver)
    {
        memcpy(mMailReceiver,mailReceiver,sizeof(*mailReceiver));
    }

private:
    MailReceiver* mMailReceiver;
    char mContent[256];
};

class MailSend
{
public:
    void sendMail(Mail* mail)
    {
        mail->showContent();
    }
};

int main()
{
    Mail* m1 = new Mail;
    m1->setContent("welcome come to bj");
    MailReceiver receiver1(1,"zhangsan"),receiver2(0,"lisi");
    m1->setReceiver(&receiver1);
    MailSend mailSend;
    mailSend.sendMail(m1);
    Mail* m2 = m1->clone();
    m2->setReceiver(&receiver2);
    mailSend.sendMail(m2);
}

welcome come to bj,Mr zhangsan
welcome come to bj,Mrs lisi

你可能感兴趣的:(原型模式)