//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;
};