Prototype原型克隆

#include <cstdlib>
#include <iostream>

using namespace std;
namespace Graphic
{
class Obj
{
  std::string name;
public:
  std::string GetName(){return name;}
  virtual void SetName(std::string& str){name = str;}
  Obj(std::string str):name(str){}
  virtual ~Obj(){cout<<"Obj 图形基类析构"<<endl;}
  virtual Obj* Clone() = 0;
  virtual Obj* Draw() = 0;
};
class Line:public Obj
{
public:
  Line(std::string str):Obj("Line" + str){}
  virtual void SetName(std::string& str)
  {
    std::string ss = "Line";
    ss += str;
    Obj::SetName(ss);
  }
  virtual ~Line(){cout<<GetName()<<" 析构"<<endl;}
  virtual Obj* Clone()
  {
    Obj* newLine = new Line(this->GetName());
    *newLine = *this;
    return newLine;
  }
  virtual Obj* Draw(){cout<<GetName()<<" 画一条线"<<endl;}
};
class Rect:public Obj
{
public:
  Rect(std::string str):Obj("Rect" + str){}
  virtual void SetName(std::string& str)
  {
    std::string ss = "Rect";
    ss += str;
    Obj::SetName(ss);
  }
  virtual ~Rect(){cout<<GetName()<<" 析构"<<endl;}
  virtual Obj* Clone()
  {
    Obj* newRect = new Rect(this->GetName());
    *newRect = *this;
    return newRect;
  }
  virtual Obj* Draw(){cout<<GetName()<<" 画一条矩形"<<endl;}
};
};
using namespace Graphic;
void DoSth(Obj*oneObj)
{
  Obj* otherObj = oneObj->Clone();
  oneObj->Draw();
  std::string str = "Two";
  otherObj->SetName(str);
  otherObj->Draw();
  delete otherObj;
}
int main(int argc, char *argv[])
{
    Obj* pLine = new Line("One");
    cout<<"------------------两条线画开始画"<<endl;
    DoSth(pLine);
    delete pLine;
    Obj* pRect = new Rect("One");
    cout<<"------------------两条矩形画开始画"<<endl;
    DoSth(pRect);
    delete pRect;
    cout<<"------------------结束"<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值