原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
用c++做此模式时,注意深拷贝与浅拷贝
//原型设计模式 #include <IOSTREAM> #include "string" using namespace std; class Prototype{ //基类提供clone接口 public: virtual Prototype * clone()=0; virtual void show() = 0; }; class Card:public Prototype{ public: Card():age(20),name("Jack"){ } Card(int mage,string mname):age(mage),name(mname){ } Card(const Card & other){ this->age = other.age; this->name = other.name; } Prototype * clone(); void show(){ cout<<"name : "<<name<<" age : "<<age<<endl; } private: int age; string name; }; Prototype * Card::clone(){ return new Card(*this); } int main(int argc, char* argv[]) { Prototype * card = new Card; card->show(); Prototype * cardcopy = card->clone(); cardcopy->show(); delete card; delete cardcopy; Prototype * card2 = new Card(100,"Mike"); card2->show(); Prototype * card2copy = card2->clone(); card2copy->show(); delete card2; delete card2copy; return 0; }
提供一个ProtoType基类以提供clone和show接口,有原型拷贝功能的类继承ProtoType类。