原型其实就是从一个对象再创建另一个对象,且不需要知道细节。如果使用原型模式,要保持灵活性,接口应该尽量丰富
例如:起始每个接口只影响一个属性,然后提供多个单一属性接口组合成的多属性接口。
#include <iostream>
#include <string>
using std::string;
using std::cout; using std::endl;
/*
因为所有的子类,即原型要使用到父类类型,ProtoType*,
所有接口还是不能够纯虚,即父类不能是抽象类。
*/
class ProtoType
{
public:
ProtoType(int age ) :m_age(age){ }
virtual void setname(const string &name,int id)
{
m_name = name;
m_id = id;
}
virtual void putout()
{
cout << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
}
virtual ProtoType* clone()
{
return this;
}
protected:
int m_id;
int m_age;
string m_name;
};
class ConcreteType1 :public ProtoType
{
public:
ConcreteType1(int age) :ProtoType(age)
{
}
virtual void setname(const string &name ,int id)override
{
m_name = name;
m_id = id;
}
void putout()
{
cout << "ConcreteType1 : " << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
}
};
class ConcreteType2 :public ProtoType
{
public:
/*调用父类构造函数,传参id,然后初始化自身。也就是拷贝了父类成员*/
ConcreteType2(int age) :ProtoType(age)
{
}
virtual void setname(const string &name,int id)override
{
m_id = id;
m_name = name;
}
void putout()
{
cout << "ConcreteType2 : " << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
}
};
int main()
{
/*原型*/
ConcreteType1 *type1 = new ConcreteType1(27);
type1->setname("张三",1101);
//新对象1
ConcreteType1 type1_2 = *(ConcreteType1*)type1->clone(); //拷贝整个对象
type1_2.setname("李四",1102);
//新对象2
ConcreteType2 type2_1 = *(ConcreteType2*)type1->clone(); //拷贝整个对象
type2_1.setname("王五", 1103);
type1->putout();
type1_2.putout();
type2_1.putout();
return 0;
}