Prototype模型:
作用:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象----克隆(clone)对象。
Prototype模型类图如下:
形象说明:如果客户想配钥匙(ConcretePrototype),就可以拿着钥匙去配钥匙的店铺,店铺老板会根据配的钥匙原型,给你配(Clone)钥匙!
具体简单的实例实现:
/*Prototype.hxx*/ #ifndef _PROTOTYPE_H_ #define _PROTOTYPE_H_ class Prototype { public: virtual ~Prototype(); virtual Prototype* Clone() const = 0; protected: Prototype(); }; class ConcretePrototype:public Prototype { public: ConcretePrototype(); ConcretePrototype(const ConcretePrototype& cp); ~ConcretePrototype(); Prototype* Clone() const; }; #endif //~_PROTOTYPE_H_
/*Prototype.cxx*/ #include "Prototype.hxx" #include <iostream> using namespace std; Prototype::Prototype() { } Prototype::~Prototype() { } Prototype* Prototype::Clone() const { return 0; } //concretePrototype ConcretePrototype::ConcretePrototype() { } ConcretePrototype::~ConcretePrototype() { } ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp) { cout<< "ConcretePrototype copy..." << endl; } Prototype* ConcretePrototype::Clone() const { return new ConcretePrototype(*this); }
/*main.cxx*/ #include "Prototype.hxx" #include <iostream> using namespace std; int main(int argc, char* argv[]) { Prototype* p = new ConcretePrototype(); Prototype* p1 = p->Clone(); cout << p <<"||" << p1 << endl; delete p; p = NULL; if (p1) { delete p1; p1 = NULL; } return 0; }
执行结果:
liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ g++ -o main main.o Prototype.o liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ ./main ConcretePrototype copy... 0xf11010||0xf11030
参考文档: