C++设计模型之五:Prototype Pattern

        Prototype模式并不是简简单单一个clone方法,Prototype模式的意义在于动态抽取当前对象运行时的状态,同时通过提供统一的clone接口方法,使得客户代码可以在不知道对象具体类型时仍然可以实现对象的拷贝,而无需运用type-switch检测对象的类型信息来分别调用创建方法来创建一个新的拷贝。
 
    使用Prototype模式,在需要复制自身来创建新产品,不需要对象的实际类型而致需要知道抽象基类即可,但是必须保证已经存在一个对象实例
 
Prototype模式典型的结构图为:
 
 
 
 
代码如下:
  1. #include<string>
  2. #include<iostream>
  3. using namespace std;
  4. class Prototype
  5. {
  6. public:
  7.  virtual ~Prototype(){};
  8.  virtual Prototype*Clone() const=0 {return 0;};
  9. protected:
  10.  Prototype(){};
  11. };
  12. class ConcreatePrototype:public Prototype
  13. {
  14. public:
  15.  ConcreatePrototype(){};
  16.  ConcreatePrototype(const ConcreatePrototype& cp)
  17.  {
  18.   cout<<"Concreate prototype"<<endl;
  19.  }
  20.  Prototype* Clone() const
  21.  {return new ConcreatePrototype(*this);};
  22. };
  23. class ConcreatePrototypeB:public Prototype
  24. {
  25. public:
  26.  ConcreatePrototypeB(){};
  27.  ConcreatePrototypeB(const string& name):filename(name)
  28.  {cout<<"Jackill,I Hate U!"<<endl;}
  29.  ConcreatePrototypeB(const ConcreatePrototypeB& cpB):filename(cpB.filename){}; 
  30.  Prototype* Clone() const
  31.  {return new ConcreatePrototypeB(*this);};
  32. private:
  33.  string filename;
  34. };
  35. void main()
  36. {
  37.  Prototype* p=new ConcreatePrototype();
  38.  Prototype* p1=p->Clone();
  39.  Prototype* p2=new ConcreatePrototypeB("Jackill");
  40.  Prototype* p3=p2->Clone();
  41. }
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值