设计模式之原型模式

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

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

优点: 

        利用原型模式比new一个对象更能提高效率。

        简化对象创建,不需要了解创建过程。

 缺点:

        深拷贝时代码实现复杂。

适用于创建新对象成本大时,利用已有的对象来复制。

代码实现:

#include <iostream>
#include <string>
using namespace std;

class ICloneable
{
	public:
		ICloneable(){}
		virtual void SetPersonalInfo(string sex,int age)
		{
			this->_age = age;
			this->_sex = sex;
		}
		virtual void SetWorkExperience(string timeArea,string company)
		{
			this->_timeArea = timeArea;
			this->_company = company;
		}
		virtual void Display()
		{
			cout << "姓名:" << _name << "性别:" << _sex << "年龄:" << _age;
			cout << "工作经历:" << _timeArea << "公司:" << _company;
		}
		virtual ICloneable* Clone() = 0;
	private:
		string _sex;
		int _age;
		string _name;
		string _timeArea;
		string _company;
};

class WorkExperice : public ICloneable
{
	public:
		WorkExperice(){}
		void SetWorkExperience(string timeArea,string company)
		{
			workData = timeArea;
			this->company = company;
		}
	private:
		string workData;
		string company;
};

class Resume : public ICloneable
{
	public:
		Resume(string name)
		{
			this->_name = name;
		}
		Resume(Resume& other)
		{
			_name = other._name;
			_age = other._age;
			_sex = other._sex;
			_timeArea = other._timeArea;
			_company = other._company;
		}
		void SetPersonalInfo(string sex,int age)
		{
			this->_age = age;
			this->_sex = sex;
		}
		void SetWorkExperience(string timeArea,string company)
		{
			this->_timeArea = timeArea;
			this->_company = company;
		}
		ICloneable* Clone()
		{
			return new Resume(*this);
		}
		void Display()
		{
			cout << "姓名:" << _name << "性别:" << _sex << "年龄:" << _age;
			cout << "工作经历:" << _timeArea << "公司:" << _company; 
		}
	private:
		string _name;
		string _sex;
		int _age;
		string _timeArea;
		string _company;
};

int main()
{
	Resume* a = new Resume("大鸟");
	ICloneable* b = a->Clone();
	
	a->SetPersonalInfo("男",29);
	a->SetWorkExperience("1998-2000","xx公司");
	a->Display();
	cout << endl;
	
	b->SetPersonalInfo("女",30);
	b->SetWorkExperience("1998-2000","xy公司");
	b->Display();
	cout << endl;
	
	
	
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值