原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。
优点:
利用原型模式比new一个对象更能提高效率。
简化对象创建,不需要了解创建过程。
缺点:
深拷贝时代码实现复杂。
适用于创建新对象成本大时,利用已有的对象来复制。
代码实现:
#include <iostream>
#include <string>
using namespace std;
class ICloneable
{
public:
ICloneable(){}
virtual void SetPersonalInfo(string sex,int age)
{
this->_age = age;
this->_sex = sex;
}
virtual void SetWorkExperience(string timeArea,string company)
{
this->_timeArea = timeArea;
this->_company = company;
}
virtual void Display()
{
cout << "姓名:" << _name << "性别:" << _sex << "年龄:" << _age;
cout << "工作经历:" << _timeArea << "公司:" << _company;
}
virtual ICloneable* Clone() = 0;
private:
string _sex;
int _age;
string _name;
string _timeArea;
string _company;
};
class WorkExperice : public ICloneable
{
public:
WorkExperice(){}
void SetWorkExperience(string timeArea,string company)
{
workData = timeArea;
this->company = company;
}
private:
string workData;
string company;
};
class Resume : public ICloneable
{
public:
Resume(string name)
{
this->_name = name;
}
Resume(Resume& other)
{
_name = other._name;
_age = other._age;
_sex = other._sex;
_timeArea = other._timeArea;
_company = other._company;
}
void SetPersonalInfo(string sex,int age)
{
this->_age = age;
this->_sex = sex;
}
void SetWorkExperience(string timeArea,string company)
{
this->_timeArea = timeArea;
this->_company = company;
}
ICloneable* Clone()
{
return new Resume(*this);
}
void Display()
{
cout << "姓名:" << _name << "性别:" << _sex << "年龄:" << _age;
cout << "工作经历:" << _timeArea << "公司:" << _company;
}
private:
string _name;
string _sex;
int _age;
string _timeArea;
string _company;
};
int main()
{
Resume* a = new Resume("大鸟");
ICloneable* b = a->Clone();
a->SetPersonalInfo("男",29);
a->SetWorkExperience("1998-2000","xx公司");
a->Display();
cout << endl;
b->SetPersonalInfo("女",30);
b->SetWorkExperience("1998-2000","xy公司");
b->Display();
cout << endl;
return 0;
}