设计模式--创建型模式--原型模式

//Creational Patterns--Prototype Pattern
//创建型模式--原型模式

//Prototype(抽象原型):定义了克隆自身的接口。
//ConcretePrototype(具体原型):被复制的对象,需要实现 Prototype 定义的接口

class Monkey
{
public:
    Monkey(){}
    virtual ~Monkey(){}
    virtual Monkey* Clone() = 0;
    virtual void Play() = 0;
};

class SunWuKong : public Monkey
{
public:
    SunWuKong(string name){m_strName = name;}
    ~SunWuKong(){}

    SunWuKong(const SunWuKong &swk)//拷贝构造函数
    {
        if(this == &swk)return;
        
        m_strName = swk.m_strName;
    }
    Monkey* Clone()
    {
        return new SunWuKong(*this);    //关键代码
    }
    void Play(){cout << m_strName << " play Golden-hoop-stick" << endl;}
private:
    string m_strName;
};

//---------------------------------------------------------
//测试
void dpPrototypeTestMain()
{
    Monkey *swp = new SunWuKong("Qi Tian Da Sheng");

    Monkey *swp1 = swp->Clone();
    Monkey *swp2 = swp1->Clone();

    swp->Play();
    swp1->Play();
    swp2->Play();

    if(swp) {delete swp; swp = NULL;}
    if(swp1) {delete swp1; swp1 = NULL;}
    if(swp2) {delete swp2; swp2 = NULL;}
    return;
};
 

猜你喜欢

转载自blog.csdn.net/hhgfg1980/article/details/82936003