设计模式实现(六)--- 原型模式(Prototype)

原型模式(Prototype),是原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。


基本的原型模式实现代码

//基本的原型模式代码
//原型类
class Prototype
{
public:
	int id1;
	int id2;
public:
	Prototype(){}
	Prototype(int id1,int id2)
	{
		this->id1 = id1;
		this->id2 = id2;
	}
	virtual Prototype *clone(){return NULL;}
};
//具体原型类,只克隆id1
class ConcretePrototype1 : public Prototype
{
public:
	ConcretePrototype1(){}
	ConcretePrototype1(int id1,int id2)
	{
		this->id1 = id1;
		this->id2 = id2;
	}
public:
	//创建当前对象的拷贝。方法是创建一个新对象,如果当前对象中只有内置数据类型或者对象类型,而没有指针类型或者引用类型(针对非内置对象,如自己创建的类)。那么直接按位或者利用赋值构造函数进行浅拷贝即可。
	//如果当前对象中有指针类型或者引用类型,则要判断是进行浅拷贝还是深拷贝,即判断是否使用不同的指针类型变量或者引用变量指向同一对象(同一块内存空间)。
	Prototype *clone()
	{
		Prototype *temp = new Prototype();
		temp->id1 = this->id1;
		return temp;
	}
};
//具体原型类,克隆id2
class ConcretePrototype2 : public Prototype
{
public:
	ConcretePrototype2(){}
	ConcretePrototype2(int id1,int id2)
	{
		this->id1 = id1;
		this->id2 = id2;
	}
public:
	Prototype *clone()
	{
		Prototype *temp = new Prototype();
		temp->id2 = this->id2;
		return temp;
	}
};
//客户端
int main()
{
	Prototype *p1 = new ConcretePrototype1(1,2);
	ConcretePrototype1 *c1 = (ConcretePrototype1 *)p1->clone();
	
	Prototype *p2 = new ConcretePrototype2(1,2);
	ConcretePrototype2 *c2 = (ConcretePrototype2 *)p2->clone();

	
	return 1;

}

原型模式例子,拷贝简历

#include <string>
#include <iostream>
using namespace std;
//一个复制简历的程序

//工作经历
class WorkExperience
{
public:
	string workDate;
	string company;
public:
	WorkExperience(string workDate,string company){this->company = company;this->workDate = workDate;}
};
//原型
class Prototype
{
public:
	Prototype(){}
	virtual Prototype *clone(){return NULL;}
};
class Resume : public Prototype
{
public:
	string name;
	string sex;
	int age;
	WorkExperience *work;
public:
	Resume()
	{
		name = "";
		sex = "";
		age = 0;
		work = NULL;
	}
	Prototype *clone()
	{
		Resume *temp = new Resume();
		temp->name = this->name;
		temp->sex = this->sex;
		temp->age = this->age;
		//浅拷贝
		//temp->work = this->work;
		
		//深拷贝
		temp->work = new WorkExperience(work->company,work->workDate);
		return (Prototype *)temp;
	}
};
int main()
{
	Resume temp;
	temp.work = new WorkExperience("西安交通大学","2014-7-23");
	Resume *c1 = (Resume *)temp.clone();
	Resume *c2 = (Resume *)temp.clone();
	return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值