设计模式C++实现六: 原型模式

本文介绍了原型模式在创建简历对象时的应用,详细解释了如何通过原型实例指定创建对象的种类,并通过拷贝这些原型来创建新的对象。重点讨论了简历类Resume的实现,包括个人资料设置、工作经验设置、显示和克隆方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式其实就是从一个对象再创建另一个可定制的对象,而且不需知道创建的具体细节。


#ifndef PROTOTYPE_H
#define PROTOTYPE_H
#include<iostream>
#include<string>
using namespace std;

class Resume
{
	string name;
	string sex;
	string age;
	string timeArea;
	string company;
public:
	Resume(){}
	~Resume(){
		cout << name << " " << sex << " " << age << endl;
		cout << "WorkExperience: " << timeArea << " " << company << " destory!\n\n";
	}
	Resume(string n) : name(n){}
	Resume(Resume & n);
	void SetPersonalInfo(string sex, string age){ this->sex = sex; this->age = age; }
	void SetWorkExperience(string T, string com){ this->timeArea = T; this->company = com; }
	void Display()const;
	Resume Clone()const;
	void operator =(Resume & res);
};

void Resume::Display()const
{
	cout << name << " " << sex << " " << age << endl;
	cout << "WorkExperience: " << timeArea << " " << company << endl;
}
Resume Resume::Clone()const
{
	Resume Temp(name);
	Temp.age = age;
	Temp.sex = sex;
	Temp.company = company;
	Temp.timeArea = timeArea;
	Temp.name = name;
	return Temp;
}
void Resume::operator =(Resume & res)
{

	age = res.age;
	sex = res.sex;
	company = res.company;
	timeArea = res.timeArea;

}

Resume::Resume(Resume & n)
{
	if (this == &n)return;
	this->age = n.age;
	this->company = n.company;
	this->timeArea = n.timeArea;
	this->sex = n.sex;
	this->name = n.name;
	
}
#endif

#include"Prototype.h"

int main()
{
	Resume a("BigBird");
	a.SetPersonalInfo("man", "29");
	a.SetWorkExperience("1998-2000", "xx company");
	a.Display();
	//使用Clone函数会有一个中间的Resume对象产生,析构时会出现两个a的析构
	//Resume b = a.Clone();
	//b.SetWorkExperience("1998-2006", "yy company");
	//b.Display();
	//使用构造函数不会有一个中间的Resume对象产生,析构时会出现只有一个a的析构,而且会在c析构后才对a析构
	Resume c(a);
	c.SetPersonalInfo("man", "24");
	c.Display();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值