Prototype模式并不是简简单单一个clone方法,Prototype模式的意义在于动态抽取当前对象运行时的状态,同时通过提供统一的clone接口方法,使得客户代码可以在不知道对象具体类型时仍然可以实现对象的拷贝,而无需运用type-switch检测对象的类型信息来分别调用创建方法来创建一个新的拷贝。
使用Prototype模式,在需要复制自身来创建新产品,不需要对象的实际类型而致需要知道抽象基类即可,但是必须保证已经存在一个对象实例
Prototype模式典型的结构图为:
代码如下:
- #include<string>
- #include<iostream>
- using namespace std;
- class Prototype
- {
- public:
- virtual ~Prototype(){};
- virtual Prototype*Clone() const=0 {return 0;};
- protected:
- Prototype(){};
- };
- class ConcreatePrototype:public Prototype
- {
- public:
- ConcreatePrototype(){};
- ConcreatePrototype(const ConcreatePrototype& cp)
- {
- cout<<"Concreate prototype"<<endl;
- }
- Prototype* Clone() const
- {return new ConcreatePrototype(*this);};
- };
- class ConcreatePrototypeB:public Prototype
- {
- public:
- ConcreatePrototypeB(){};
- ConcreatePrototypeB(const string& name):filename(name)
- {cout<<"Jackill,I Hate U!"<<endl;}
- ConcreatePrototypeB(const ConcreatePrototypeB& cpB):filename(cpB.filename){};
- Prototype* Clone() const
- {return new ConcreatePrototypeB(*this);};
- private:
- string filename;
- };
- void main()
- {
- Prototype* p=new ConcreatePrototype();
- Prototype* p1=p->Clone();
- Prototype* p2=new ConcreatePrototypeB("Jackill");
- Prototype* p3=p2->Clone();
- }