一、我的描述
什么是原型模式,按我的理解就是对一个对象的N个克隆。克隆出来的东西应该是一模一样,当然你也可以修改你克隆出来的对象的内容。对C++来说,表现就是拷贝构造函数。这个模式比较简单,就不再罗嗦。
二、UML 图
三、我的代码
#include<iostream> using namespace std; #include <string> class WorkExperience { public: WorkExperience(string n) : name(n) {} WorkExperience() {} void SetName(string n) { name = n;} string GetName() { return name; } void SetDate(string d) { date = d; } string GetDate() { return date; } void SetCompany (string c) { company = c; } string GetCompany() { return company; } private: string name; string date; string company; }; class Resume : public WorkExperience { public: Resume (string n) : WorkExperience(n) {} Resume (Resume& r) { SetName(r.GetName()); SetDate(r.GetDate()); SetCompany(r.GetCompany()); } Resume* Clone() { return new Resume(*this); } }; int main() { Resume *p_resume1 = new Resume("george"); p_resume1->SetDate("2003"); p_resume1->SetCompany("xxx"); Resume *p_resume2 = p_resume1->Clone(); p_resume2->SetDate("2004"); p_resume2->SetCompany("yyy"); cout << "Resume 1: " << p_resume1->GetName() << " " << p_resume1->GetDate() << " " << p_resume1->GetCompany() << endl; delete p_resume1; cout << "Resume 2: " << p_resume2->GetName() << " " << p_resume2->GetDate() << " " << p_resume2->GetCompany() << endl; delete p_resume2; }