设计模式c++

原型模式

//原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。
//原型模式就是用来克隆对象的。
#include <iostream>
#include <string>
using namespace std;

class WorkExperience {
public:
	string workDate;
	string company;
public:
	void setWorkDate(string v) {
		workDate = v;
	}
	string getWorkDate() {
		return workDate;
	}

	void setCompany(string c) {
		company = c;
	}

	string getCompany() {
		return company;
	}
};

class resume {
public:

	char * name;
	string sex;
	string age;
	WorkExperience work;
	//string timeArea;
	//string company;
public:
	resume() {
		
		//this->name = name;
	}
	~resume() {
		delete[] name;
	}
	void setName(string name) {
		int sz = name.size();
		this->name = new char[sz + 1];
		memcpy(this->name, name.c_str(), sz);
		this->name[sz] = '\0';
	}

	void setPersonalInfo(string sex,string age) {
		this->sex = sex;
		this->age = age;
	}

	void setWorkExperience(string timeArea,string Company) {
		work.company = Company;
		work.workDate = timeArea;
		//this->timeArea = timeArea;
		//this->company = Company;
	}

	void Display() {
		cout << "{" << name << "} " << "{" << sex << "} " << "{" << age << "}" << endl;
		//cout << "工作经历:" << "{" << timeArea << "} " << "{" << company << "}" << endl;
		cout << "工作经历:" << "{" << work.workDate << "} " << "{" << work.company << "}" << endl;
	}

	resume* clone() {
		resume* res = new resume();
		*res = *this;
		res->setName(this->name);//深拷贝,去掉delete a会有double free问题
		return res;
	}
};

int main() {
	resume* a = new resume();
	a->setName("大鸟");
	a->setPersonalInfo("男","29");
	a->setWorkExperience("1998-2000","XX公司");
	resume* b = a->clone();
	b->setWorkExperience("1998-2006","YY公司");
	resume* c = b->clone();
	c->setWorkExperience("1998-2006", "ZZ公司");
	//cout<<c->name.
	a->Display();
	b->Display();
	c->Display();
	delete a;
	delete b;
	delete c;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值