设计模式(6)--原型模式
2016-11-03 00:37 sylar_liang 阅读(189) 评论(0) 编辑 收藏 举报//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(); }
//6.原型模式 //ver2 //首先抽象一个基类 class Resume { protected: string _name; public: Resume(){} virtual ~Resume(){} virtual void set(const string name) { _name = name; } virtual void show(){} virtual Resume * clone() { return 0; } }; class ResumeA : public Resume { public: ResumeA(string name) { _name = name; } ResumeA(const ResumeA & r) { _name = r._name; } ~ResumeA() { } ResumeA * clone() { return new ResumeA(*this); } void show() { cout << "ResumeA name" << _name <<endl; } }; class ResumeB : public Resume { public: ResumeB(string name) { _name = name; } ResumeB(const ResumeB& r) { _name = r._name; } ~ResumeB() { } ResumeB * clone() { return new ResumeB(*this); } void show() { cout << "ResumeB name" << _name <<endl; } }; void main21() { Resume * r1 = new ResumeA("A"); Resume * r2 = new ResumeB("B"); Resume * r3 = r1->clone(); Resume * r4 = r2->clone(); r1->show(); r2->show(); //删除r1,r2 delete r1; delete r2; r1 = r2 = NULL; //深拷贝所以对r3,r4无影响. r3->show(); r4->show(); delete r3; delete r4; r3 = r4 = NULL; }
//操作步骤:
//1.声明一个抽象基类,并定义clone()函数未纯虚函数。
//2.实例化各个子类,并且实现复制构造函数,并实现clone()函数.