Prototype原型模式

Prototype原型模式。用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。
       原型模式就是用一個對象來創建另一個相同的對象而無需知道創建的具體細節。而且大大提高了創建的效率。優點主要是這兩個:
  1. 屏蔽創建的具體細節,如參數等。
  2. 創建的效率高。因爲不必調用構造函數等。
       原型模式也是一種創建型模式,跟建造者模式,工廠模式系類一樣,不同的是,建造者模式側重於一步一步建造對象,工廠模式側重於多個類的依賴。相同的是都是通過一個類(對象實例)來專門負責對象的創建工作。

     使用原型模式要先了解下拷貝構造函數的深拷貝和淺拷貝。

代碼:
//Prototype.h
  1. #include "stdafx.h"  
  2. #include<iostream>  
  3. #include<cstring>  
  4. using namespace std;  
  5. class Prototype  
  6. {  
  7. public:  
  8.     virtual ~Prototype()  
  9.     {  
  10.         cout << "~Prototype" << endl;  
  11.     }  
  12.     virtual Prototype* clone()const = 0;  
  13.     virtual void show()const = 0;  
  14. };  
  15.   
  16. class ConcreteProtype1 :public Prototype  
  17. {  
  18. public:  
  19.     ConcreteProtype1(int len,char*str)  
  20.     {  
  21.         _length = len;  
  22.         _str = new char[_length];  
  23.         strcpy_s(_str, _length, str);  
  24.     }  
  25.     ~ConcreteProtype1()  
  26.     {  
  27.         delete(_str);  
  28.         cout << "~ConcreteProtype" << endl;  
  29.     }  
  30.   
  31.     ConcreteProtype1(const ConcreteProtype1& rhs)  
  32.     {  
  33.         //實現深拷貝  
  34.         _length = rhs._length;  
  35.         _str = new char[_length];  
  36.         if (_str != NULL)  
  37.             strcpy_s(_str, _length, rhs._str);  
  38.         cout << "copy construct ConcreteProtype1" << endl;  
  39.     }  
  40.     virtual Prototype* clone()const  
  41.     {  
  42.         return new ConcreteProtype1(*this);  
  43.     }  
  44.   
  45.     virtual void show()const  
  46.     {  
  47.         cout <<"value:"<< _str << endl;  
  48.         cout << "Address:" << &_str << endl;  
  49.     }  
  50. private:  
  51.     int _length;  
  52.     char* _str;  
  53. };  

  1. // PrototypePattern.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "Prototype.h"  
  6.   
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.   
  11.     Prototype* p1 = new ConcreteProtype1(6,"hello");  
  12.     Prototype *p2 = p1->clone();  
  13.     p1->show();  
  14.     p2->show();  
  15.     getchar();  
  16.     return 0;  
  17. }  

發佈了7 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章