//6.原型模式 //ver1 //原型模式: 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 //原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。 //虚基类 class Prototype { public: Prototype(){} virtual ~Prototype(){} virtual Prototype * clone() = 0; }; class ConcretePrototype1 : public Prototype { public: ConcretePrototype1() { cout << "ConcretePrototype1 create" << endl; } ConcretePrototype1(const ConcretePrototype1 &) { cout << "ConcretePrototype1 copy" << endl; } virtual ~ConcretePrototype1() { cout << "ConcretePrototype1 destruction" << endl; } virtual Prototype * clone() { return new ConcretePrototype1(*this); } }; class ConcretePrototype2 : public Prototype { public: ConcretePrototype2() { cout << "ConcretePrototype2 create" << endl; } ConcretePrototype2(const ConcretePrototype2 &) { cout << "ConcretePrototype1 copy" << endl; } virtual ~ConcretePrototype2() { cout << "ConcretePrototype2 destruction" << endl; } virtual Prototype * clone() { return new ConcretePrototype2(*this); } }; void main1() { Prototype *ptype1 = new ConcretePrototype1(); Prototype *copytype1 = ptype1->clone(); }
时间: 2024-10-11 14:35:04