//6.原型模式 //ver1 //原型模式: 用原型實例指定建立對象的種類,而且經過拷貝這些原型建立新的對象。 //原型模式其實就是從一個對象再建立另一個可定製的對象,並且不需知道任何建立的細節。 //虛基類 class Prototype { public: Prototype(){} virtual ~Prototype(){} virtual Prototype * clone() = 0; }; class ConcretePrototype1 : public Prototype { public: ConcretePrototype1() { cout << "ConcretePrototype1 create" << endl; } ConcretePrototype1(const ConcretePrototype1 &) { cout << "ConcretePrototype1 copy" << endl; } virtual ~ConcretePrototype1() { cout << "ConcretePrototype1 destruction" << endl; } virtual Prototype * clone() { return new ConcretePrototype1(*this); } }; class ConcretePrototype2 : public Prototype { public: ConcretePrototype2() { cout << "ConcretePrototype2 create" << endl; } ConcretePrototype2(const ConcretePrototype2 &) { cout << "ConcretePrototype1 copy" << endl; } virtual ~ConcretePrototype2() { cout << "ConcretePrototype2 destruction" << endl; } virtual Prototype * clone() { return new ConcretePrototype2(*this); } }; void main1() { Prototype *ptype1 = new ConcretePrototype1(); Prototype *copytype1 = ptype1->clone(); }
//6.原型模式 //ver2 //首先抽象一個基類 class Resume { protected: string _name; public: Resume(){} virtual ~Resume(){} virtual void set(const string name) { _name = name; } virtual void show(){} virtual Resume * clone() { return 0; } }; class ResumeA : public Resume { public: ResumeA(string name) { _name = name; } ResumeA(const ResumeA & r) { _name = r._name; } ~ResumeA() { } ResumeA * clone() { return new ResumeA(*this); } void show() { cout << "ResumeA name" << _name <<endl; } }; class ResumeB : public Resume { public: ResumeB(string name) { _name = name; } ResumeB(const ResumeB& r) { _name = r._name; } ~ResumeB() { } ResumeB * clone() { return new ResumeB(*this); } void show() { cout << "ResumeB name" << _name <<endl; } }; void main21() { Resume * r1 = new ResumeA("A"); Resume * r2 = new ResumeB("B"); Resume * r3 = r1->clone(); Resume * r4 = r2->clone(); r1->show(); r2->show(); //刪除r1,r2 delete r1; delete r2; r1 = r2 = NULL; //深拷貝因此對r3,r4無影響. r3->show(); r4->show(); delete r3; delete r4; r3 = r4 = NULL; }
//操做步驟:
//1.聲明一個抽象基類,並定義clone()函數未純虛函數。
//2.實例化各個子類,而且實現複製構造函數,並實現clone()函數.函數