原型模式
//原型模式(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;
}