[C++]原型模式

用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象

C++ 代码如下:

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式 - 原型模式

// 原型模式,通过默认拷贝构造函数,通过clone接口,new一个新的对象

#include <iostream>

using namespace std;

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif

class Prototype {
public:
	Prototype() {}

	virtual void SetID(string id) = 0;

	virtual string GetID() = 0;

	virtual Prototype* Clone() = 0;

protected:
	string id_ = "";
};

class ConcreatePrototype : Prototype {
public :
	ConcreatePrototype(string id){
		id_ = id;
	}

	void SetID(string id) {
		id_ = id;
	}

	string GetID() {
		return id_;
	}

	Prototype* Clone() {
		// 根据当前对象 拷贝构造一个新对象(浅拷贝)
		return new ConcreatePrototype(*this);

		/*
		ConcreatePrototype* prototype = new ConcreatePrototype("p");
		*prototype = *this;
		return prototype;
		*/
	}
};

int main()
{
	ConcreatePrototype* p1 = new ConcreatePrototype("p1");
	ConcreatePrototype* p2 = (ConcreatePrototype*)p1->Clone();

	// 此处p2对象的成员变量均为p1对象的成员变量的值
	cout << "p1: " << p1 << endl;
	cout << "p1 id: " << p1->GetID() << endl;
	cout << "p2: " << p2 << endl;
	cout << "p2 id: " << p2->GetID() << endl;

	cout << "--------------------\n";
	// P1和P2各自调用自己的方法
	p1->SetID("p1 set");
	p2->SetID("p2 set");
	cout << "p1 id: " << p1->GetID() << endl;
	cout << "p2 id: " << p2->GetID() << endl;

	SAFE_DELETE(p2)
	SAFE_DELETE(p1)

	return 0;
}


github源码路径:https://github.com/dangwei-90/Design-Mode

持续更新中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值