C++实现 原型模式(0) - 创建型

// 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创建的原型,拥有独立的地址空间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值