大话设计模式原型模式c++实现

本文深入探讨设计模式中的原型模式,通过C++语言详细阐述其实现原理与应用。

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

原型模式

其他二十三种设计模式

#include<iostream>

using namespace std;

//原型模式(Prototype)
class Person {
public:
	virtual Person* Clone() = 0;
};

class WorkExperience :public Person{
public:
	WorkExperience() {}
	~WorkExperience() {}
	WorkExperience(string _workDate,string _company) {
		this->workDate = _workDate;
		this->company = _company;
	}
	//深拷贝--拷贝构造函数,使用引用
	WorkExperience(const WorkExperience& r) {  
		workDate = r.workDate;
		company = r.company;
	}
	void DisPlay() {
		cout << "工作经历: " << workDate << " " << company << endl;
	}
	virtual Person* Clone() {
		/*浅拷贝
		WorkExperience* tmp = new WorkExperience;
		*tmp = *this;    
		return tmp;*/
		return new WorkExperience(*this);   //调用拷贝构造函数
	}

private:
	string workDate;
	string company;
};

class Resume :public Person {
public:
	Resume(string _name) {
		this->name = _name;
	}
	Resume(WorkExperience* _work) {
		this->work = (WorkExperience*)_work->Clone();
	}
	void SetPersonaInfo(string _sex,string _age) {
		this->sex = _sex;
		this->age = _age;
	}
	void SetWorkExperience(string _workDate,string _company) {
		work = new WorkExperience(_workDate, _company);
	}
	void DisPlay() {
		cout << name << " " << sex << " " << age << endl;
		work->DisPlay();
	}
	virtual Person* Clone() {
		Resume* obj = new Resume(*this);
		obj->name = this->name;
		obj->sex = this->sex;
		obj->age = this->age;
		return obj;
	}

private:
	string name;
	string sex;
	string age;
	WorkExperience* work;
};

void test1() {
	Resume* a = new Resume("大鸟");
	a->SetPersonaInfo("男", "29");
	a->SetWorkExperience("1998-2000", "XX公司");

	Resume* b = (Resume*)a->Clone();
	b->SetWorkExperience("1998-2006", "YY公司");

	Resume* c = (Resume*)a->Clone();
	c->SetPersonaInfo("男", "24");
	c->SetWorkExperience("1998-2003", "ZZ公司");

	a->DisPlay();
	b->DisPlay();
	c->DisPlay();

	delete a;
	delete b;
	delete c;
}

int main() {
	test1();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值