- #include<string>
- #include<iostream>
- using namespace std;
- class Prototype
- {
- public:
- virtual ~Prototype(){};
- virtual Prototype*Clone() const=0 {return 0;};
- protected:
- Prototype(){};
- };
- class ConcreatePrototype:public Prototype
- {
- public:
- ConcreatePrototype(){};
- ConcreatePrototype(const ConcreatePrototype& cp)
- {
- cout<<"Concreate prototype"<<endl;
- }
- Prototype* Clone() const
- {return new ConcreatePrototype(*this);};
- };
- class ConcreatePrototypeB:public Prototype
- {
- public:
- ConcreatePrototypeB(){};
- ConcreatePrototypeB(const string& name):filename(name)
- {cout<<"Jackill,I Hate U!"<<endl;}
- ConcreatePrototypeB(const ConcreatePrototypeB& cpB):filename(cpB.filename){};
- Prototype* Clone() const
- {return new ConcreatePrototypeB(*this);};
- private:
- string filename;
- };
- void main()
- {
- Prototype* p=new ConcreatePrototype();
- Prototype* p1=p->Clone();
- Prototype* p2=new ConcreatePrototypeB("Jackill");
- Prototype* p3=p2->Clone();
- }
C++設計模型之五:Prototype Pattern
Prototype模式並不是簡簡單單一個clone方法,Prototype模式的意義在於動態抽取當前對象運行時的狀態,同時通過提供統一的clone接口方法,使得客戶代碼可以在不知道對象具體類型時仍然可以實現對象的拷貝,而無需運用type-switch檢測對象的類型信息來分別調用創建方法來創建一個新的拷貝。
使用Prototype模式,在需要複製自身來創建新產品,不需要對象的實際類型而致需要知道抽象基類即可,但是必須保證已經存在一個對象實例
Prototype模式典型的結構圖爲:
代碼如下:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.