原型模式
对象的构造使用clone成员函数,而不是对象的构造函数。这样的好处在于:clone函数可以被定义为虚函数,而构造函数不可以。Prototype方法不限制接口的数量。但是对于每个派生关系,基类和派生类都要包含clone函数。clone函数在基类中定义为纯虚函数,具体的clone函数留在派生类里实现。另外定义一个director类,这个类负责接收具体类型信息,然后根据信息生成相应的对象。在使用这种方法前,必须提供具体的派生类型给这个director类。我们可以假设在创造一个克隆体,而且克隆出来的对象会拥有原来对象的全部特征,而且在后面也能够进行操作。
#include <iostream>
#include <cstring>
using namespace std;
class IPrototype
{
public:
virtual ~IPrototype(){}
virtual IPrototype *clone()=0;
virtual void print()=0;
};
class Prototype : public IPrototype
{
public:
Prototype(){
this->name = "";
this->age = 0;
this->des = NULL;
}
Prototype(string name, int age, char *des){
this->name = name;
this->age = age;
this->des = des;
}
IPrototype *clone(){
Prototype *ip = new Prototype();
ip->name = this->name;
ip->age = this->age;
ip->des = this->des;
return ip;
}
void print(){
cout<<name<<":"<<age<<":"<<des<<endl;
}
private:
string name;
int age;
char *des;
};
int main()
{
IPrototype *ip1 = new Prototype("Peter",22,"master");
IPrototype *ip2 = ip1->clone();
ip1->print();
ip2->print();
cout<<ip1<<":"<<ip2<<endl;
return 0;
}