使用场景
资源优化场景。
类初始化需要消化非常多的资源,这个资源包括数据、硬件资源等。
性能和安全要求的场景。
通过 new 产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。
一个对象多个修改者的场景。
一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用。
在实际项目中,原型模式很少单独出现,一般是和工厂方法模式一起出现,通过 clone 的方法创建一个对象,然后由工厂方法提供给调用者。
#include<iostream>
using namespace std;
class Prototype
{
public:
virtual ~Prototype() {}
virtual Prototype* Clone() const = 0;
protected:
Prototype() {}
private:
};
Prototype* Prototype::Clone() const
{
return nullptr;
};
class ConcretePrototype : public Prototype
{
public:
ConcretePrototype() {}
ConcretePrototype(const ConcretePrototype& cp) { cout << "ConcretePrototype copy..." << endl; }
~ConcretePrototype() {}
Prototype* Clone() const { return new ConcretePrototype(*this); }
protected:
private:
};
int main(int argc, char* argv[])
{
Prototype* p = new ConcretePrototype();
Prototype* p1 = p->Clone();
return 0;
}
0 评论