原型模式(Prototype):用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
原型模式的clone()函数,对于c++来说其实就是拷贝构造函数,要注意是否需要深拷贝。
例子:在制作简历的时候我们会先制作一份模板,然后在复印这份模板,但是针对不同的公司侧重点可能不同,因此需要对简历的某些地方进行修改。
UML:
//工作经历
class WorkExperice {
private:
string m_date;
string m_company;
public:
string GetDate()
{
return m_date;
}
void SetDate(string date)
{
m_date = date;
}
string GetCompany()
{
return m_company;
}
void SetCompany(string company)
{
m_company = company;
}
};
//简历
class Resume {
private:
string m_name;
WorkExperice *work;
public:
Resume(string name)
{
work = new WorkExperice();
m_name = name;
}
Resume(const Resume &R) //拷贝构造函数
{
m_name = R.m_name;
//work = R.work; //浅拷贝,同一个对象,修改后都会改变
WorkExperice *temp = new WorkExperice(); //深拷贝
work = temp;
}
void SetWorkExperice(string date, string company)
{
work->SetDate(date);
work->SetCompany(company);
}
void show()
{
cout << m_name << work->GetDate() << work->GetCompany()<<endl;
}
Resume* clone() //相当于执行拷贝构造函数的工作
{
return new Resume(*this);
}
};
int main()
{
Resume *A = new Resume("yu");
A->SetWorkExperice("20","CompanyA");
Resume *B = A->clone();
B->SetWorkExperice("21", "CompanyB");
A->show(); B->show(); //修改B不会影响A
system("pause");
return 0;
}