原型模式
原型模式定义
定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
看uml图:
原型模式就是将对象再创建一个定制对象,而且我们不需要知道创建的细节。
原型模式c++实现
由于c++中没有像c#那样ICloneable接口,所以我们可以自己定义一个clone接口类。
我们举一个栗子:简历的复制,我现在需要简历,正常来说我们需要建立一个简历类,设置个人信息,公司经历等。然后就开始实例化,但是如果我需要多份不同的简历,我就需要实例化多个对象,需要几份就需要new几份初始化。造成资源的浪费。
现在我们用原型模式,uml图:
看代码:(建议copy本地跑一下)
#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
class Cloneinterface{
virtual Cloneinterface* clone() = 0;
};
class WorkExperience: public Cloneinterface{
public:
string workDate;
string Company;
WorkExperience(){};
WorkExperience* operator=(const WorkExperience* work){
workDate = work->workDate;
Company = work->Company;
}
WorkExperience *clone(){
return new WorkExperience(*this);
}
};
class Resume : public Cloneinterface{
private:
string name;
string sex;
int age;
WorkExperience* work;
public:
Resume(){}
Resume(string name){
this->name = name;
work = new WorkExperience;
}
Resume(WorkExperience* work){
this->work = work->clone();
}
~Resume(){}
void SerPersonalInfo(string sex,int age){
this->sex = sex;
this->age = age;
}
void SetWorkExperience(string timeArea,string company){
work->workDate = timeArea;
work->Company = company;
}
void Display(){
cout<<"{"<<name<<"}"<<"{"<<sex<<"}"<<"{"<<age<<"}"<<endl;
cout<<"工作经历:"<<"{"<<work->workDate<<"}"<<"{"<<work->Company<<"}"<<endl;
}
Resume* clone(){
Resume* obj = new Resume(this->work);
obj->name = this->name;
obj->sex = this->sex;
obj->age = this->age;
return obj;
}
};
int main(){
Resume* a = new Resume("ts");
a->SerPersonalInfo("boy",20);
a->SetWorkExperience("2012/02-2014/05","ttt");
a->Display();
Resume* b = a->clone();
b->SerPersonalInfo("girl",19);
b->SetWorkExperience("2015/06-2017/09","sss");
b->Display();
// delete a;
// delete b;
// a->Display();
}