#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;
}