Prototype原型模式。用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。
原型模式就是用一個對象來創建另一個相同的對象而無需知道創建的具體細節。而且大大提高了創建的效率。優點主要是這兩個:
- 屏蔽創建的具體細節,如參數等。
- 創建的效率高。因爲不必調用構造函數等。
原型模式也是一種創建型模式,跟建造者模式,工廠模式系類一樣,不同的是,建造者模式側重於一步一步建造對象,工廠模式側重於多個類的依賴。相同的是都是通過一個類(對象實例)來專門負責對象的創建工作。
使用原型模式要先了解下拷貝構造函數的深拷貝和淺拷貝。
代碼:
//Prototype.h
-
#include "stdafx.h"
-
#include<iostream>
-
#include<cstring>
-
using namespace std;
-
class Prototype
-
{
-
public:
-
virtual ~Prototype()
-
{
-
cout << "~Prototype" << endl;
-
}
-
virtual Prototype* clone()const = 0;
-
virtual void show()const = 0;
-
};
-
-
class ConcreteProtype1 :public Prototype
-
{
-
public:
-
ConcreteProtype1(int len,char*str)
-
{
-
_length = len;
-
_str = new char[_length];
-
strcpy_s(_str, _length, str);
-
}
-
~ConcreteProtype1()
-
{
-
delete(_str);
-
cout << "~ConcreteProtype" << endl;
-
}
-
-
ConcreteProtype1(const ConcreteProtype1& rhs)
-
{
-
-
_length = rhs._length;
-
_str = new char[_length];
-
if (_str != NULL)
-
strcpy_s(_str, _length, rhs._str);
-
cout << "copy construct ConcreteProtype1" << endl;
-
}
-
virtual Prototype* clone()const
-
{
-
return new ConcreteProtype1(*this);
-
}
-
-
virtual void show()const
-
{
-
cout <<"value:"<< _str << endl;
-
cout << "Address:" << &_str << endl;
-
}
-
private:
-
int _length;
-
char* _str;
-
};
-
-
-
-
#include "stdafx.h"
-
#include "Prototype.h"
-
-
-
int _tmain(int argc, _TCHAR* argv[])
-
{
-
-
Prototype* p1 = new ConcreteProtype1(6,"hello");
-
Prototype *p2 = p1->clone();
-
p1->show();
-
p2->show();
-
getchar();
-
return 0;
-
}