原型模式是创建型模式的一种,其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。
#include <iostream>
class Prototype
{
public:
virtual Prototype* Clone() const = 0;
virtual ~Prototype() { std::cout << "~Prototype" << std::endl; }
protected:
Prototype() { std::cout << "Prototype" << std::endl; }
};
class ConcretePrototype1 : public Prototype
{
public:
ConcretePrototype1() { std::cout << "ConcretePrototype1" << std::endl;}
ConcretePrototype1(const ConcretePrototype1 &obj) { std::cout << "copy ConcretePrototype1" << std::endl; }
Prototype* Clone() const
{
return new ConcretePrototype1(*this);
}
};
class ConcretePrototype2 : public Prototype
{
public:
ConcretePrototype2() { }
ConcretePrototype2(const ConcretePrototype2 & obj) { }
Prototype* Clone() const
{
return new ConcretePrototype2(*this);
}
};
int main(void)
{
Prototype *pro1 = new ConcretePrototype1();
Prototype *pro2 = pro1->Clone();
delete pro1;
delete pro2;
return 0;
}