1.目的
当需要从一个对象copy出另外一个对象时,可以使用原型模式,本质上是调用的copy构造函数
与copy构造函数的区别,可能就是不需要显示的生成对象,而是通过函数调用(?)
2.代码
prototype.h
#ifndef PROTOTYPE_H_
#define PROTOTYPE_H_
#include <string>
#include <iostream>
using namespace std;
class Resume
{
public:
Resume(string name, string sex, string age):name(name), sex(sex),age(age)
{}
Resume(const Resume& arg)
{
this->name = arg.name;
this->age = arg.age;
this->sex = arg.sex;
this->workExperience = arg.workExperience;
}
void setWorkExperience(string arg)
{
workExperience = arg;
}
Resume& clone() const
{
return *(new Resume(*this));
}
void show()
{
cout<<name<<" "<<sex<<" "<<age<<endl;
cout<<workExperience<<endl;
}
private:
string name;
string sex;
string age;
string workExperience;
};
#endif /* PROTOTYPE_H_ */
prototype.cpp
#include "ProtoType.h"
void protoType()
{
Resume a("Tom", "male", "30");
a.setWorkExperience("1998-2000, Company A");
Resume b = a.clone();
b.setWorkExperience("2000-2002, Company B");
Resume c = a.clone();
c.setWorkExperience("2002-2004, Company C");
a.show();
b.show();
c.show();
}
执行效果:
Tom male 30
1998-2000, Company A
Tom male 30
2000-2002, Company B
Tom male 30
2002-2004, Company C