// 5_Prototype_1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/**
* 原型模式就是从一个对象再创建另外一个
* 可定制的对象,而且不需要知道任何创建的细节。
**/
class Prototype
{
private:
string _ID;
public:
Prototype(string id)
{
_ID = id;
}
string GetID(){ return _ID; }
public:
virtual Prototype* Clone(){ return nullptr; }
};
class ConcretePrototype1 : public Prototype
{
public:
ConcretePrototype1(string id) :Prototype(id){}
Prototype* Clone() override
{
return new ConcretePrototype1(*this);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ConcretePrototype1* p1 = new ConcretePrototype1("I"); // P1是新创建的对象
ConcretePrototype1* c1 = (ConcretePrototype1*)p1->Clone(); // c1是P1克隆出来的对象 - 实现原型模式
ConcretePrototype1* p2 = p1; // p2是指向P1的地址的,和P1是同一个地址
cout << "p1= " << p1 << endl;
cout << "c1= " << c1 << endl;
cout << "p2= " << p2 << endl;
return 0;
}
运行结果:
观察地址可发现P2并非创建的原型,P2是指向P1的,和P1拥有同一个地址空间;
C1才是通过P1创建的原型,拥有独立的地址空间