C++設計模型之五:Prototype Pattern

       Prototype模式並不是簡簡單單一個clone方法,Prototype模式的意義在於動態抽取當前對象運行時的狀態,同時通過提供統一的clone接口方法,使得客戶代碼可以在不知道對象具體類型時仍然可以實現對象的拷貝,而無需運用type-switch檢測對象的類型信息來分別調用創建方法來創建一個新的拷貝。
 
    使用Prototype模式,在需要複製自身來創建新產品,不需要對象的實際類型而致需要知道抽象基類即可,但是必須保證已經存在一個對象實例
 
Prototype模式典型的結構圖爲:
 
 
 
 
代碼如下:
  1. #include<string>
  2. #include<iostream>
  3. using namespace std;
  4. class Prototype
  5. {
  6. public:
  7.  virtual ~Prototype(){};
  8.  virtual Prototype*Clone() const=0 {return 0;};
  9. protected:
  10.  Prototype(){};
  11. };
  12. class ConcreatePrototype:public Prototype
  13. {
  14. public:
  15.  ConcreatePrototype(){};
  16.  ConcreatePrototype(const ConcreatePrototype& cp)
  17.  {
  18.   cout<<"Concreate prototype"<<endl;
  19.  }
  20.  Prototype* Clone() const
  21.  {return new ConcreatePrototype(*this);};
  22. };
  23. class ConcreatePrototypeB:public Prototype
  24. {
  25. public:
  26.  ConcreatePrototypeB(){};
  27.  ConcreatePrototypeB(const string& name):filename(name)
  28.  {cout<<"Jackill,I Hate U!"<<endl;}
  29.  ConcreatePrototypeB(const ConcreatePrototypeB& cpB):filename(cpB.filename){}; 
  30.  Prototype* Clone() const
  31.  {return new ConcreatePrototypeB(*this);};
  32. private:
  33.  string filename;
  34. };
  35. void main()
  36. {
  37.  Prototype* p=new ConcreatePrototype();
  38.  Prototype* p1=p->Clone();
  39.  Prototype* p2=new ConcreatePrototypeB("Jackill");
  40.  Prototype* p3=p2->Clone();
  41. }
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章