原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式其实就是从一个对象再创建另一个可定制的对象,而且不需知道创建的具体细节。
#ifndef PROTOTYPE_H #define PROTOTYPE_H #include<iostream> #include<string> using namespace std; class Resume { string name; string sex; string age; string timeArea; string company; public: Resume(){} ~Resume(){ cout << name << " " << sex << " " << age << endl; cout << "WorkExperience: " << timeArea << " " << company << " destory!\n\n"; } Resume(string n) : name(n){} Resume(Resume & n); void SetPersonalInfo(string sex, string age){ this->sex = sex; this->age = age; } void SetWorkExperience(string T, string com){ this->timeArea = T; this->company = com; } void Display()const; Resume Clone()const; void operator =(Resume & res); }; void Resume::Display()const { cout << name << " " << sex << " " << age << endl; cout << "WorkExperience: " << timeArea << " " << company << endl; } Resume Resume::Clone()const { Resume Temp(name); Temp.age = age; Temp.sex = sex; Temp.company = company; Temp.timeArea = timeArea; Temp.name = name; return Temp; } void Resume::operator =(Resume & res) { age = res.age; sex = res.sex; company = res.company; timeArea = res.timeArea; } Resume::Resume(Resume & n) { if (this == &n)return; this->age = n.age; this->company = n.company; this->timeArea = n.timeArea; this->sex = n.sex; this->name = n.name; } #endif
#include"Prototype.h" int main() { Resume a("BigBird"); a.SetPersonalInfo("man", "29"); a.SetWorkExperience("1998-2000", "xx company"); a.Display(); //使用Clone函数会有一个中间的Resume对象产生,析构时会出现两个a的析构 //Resume b = a.Clone(); //b.SetWorkExperience("1998-2006", "yy company"); //b.Display(); //使用构造函数不会有一个中间的Resume对象产生,析构时会出现只有一个a的析构,而且会在c析构后才对a析构 Resume c(a); c.SetPersonalInfo("man", "24"); c.Display(); return 0; }
原文地址:http://blog.csdn.net/shiwazone/article/details/45647545