今天来学习一下原型模式,咋看这个名字感觉有点抽象。原型模式定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。下面看一下C++代码实现。
#include <iostream>
#include <string>
#include <list>
#include <math.h>
#include <stdlib.h>
using namespace std;
//原型模式:浅复制
class Cloneable
{
virtual Cloneable *clone()
{
return new Cloneable();
}
};
class Resume : Cloneable
{
public:
Resume(string name)
{
this->name = name;
}
void SetPersonInfo(string sex,string age)
{
this->sex = sex;
this->age = age;
}
void Display()
{
cout << name << "," << sex << "," << age << endl;
}
Resume *Clone()
{
return new Resume(*this);
}
private:
string name;
string sex;
string age;
};
int main()
{
Resume *a = new Resume("zhangsan");
a->SetPersonInfo("man","22");
Resume *b = (Resume *)a->Clone();
a->SetPersonInfo("man","23");
a->Display();
b->Display();
delete a;
delete b;
return 0;
}
上面是一个填写个人信息的类,如果有多个人,每个人的信息都不一样,不用原型模式的clone就要在main函数中new很多次,这样性能太低了。一般在初始化的信息不发生变化的情况下,克隆是最好的办法。这即隐藏了对象的创建细节,又对性能是大大的提高。
参考资料:大话设计模式