原型模式的目的是:以现有对象为原型,通过深拷贝创建一个新对象。
先来看看模式图。
原型模式本质上就是深拷贝问题的解决方案——通过定义一个克隆接口,以已有对象为原型,构造出一个新对象。
class ProtoType
{
public:
virtual Product*Clone() = 0;
};
class Product:public ProtoType
{
public:
string _name = "A";
virtual Product*Clone()override
{
Product*ret = new Product;
ret->_name = this->_name;
return ret;
}
};
int main(int argc, char *argv[])
{
Product* a = new Product;
Product *b = a->Clone();
system("pause");
return 0;
}