#include <iostream.h>
#include <string.h>
//此练习为原型模式方法的练习
//原型模式揭示了在同一原型上可以通过复制使得
//只需要实例化一次,再通过相应的类函数操作可以得到
//同一原型下的不同的版本对象
//此练习将考虑在实际开发中 比如 工作经历也是作为一个类被含在简历类中的情况
//这情况将涉及到类的引用和深、浅复制
//原型基类:简历
class Resume
{
protected:
char *name;
public:
Resume(){}
virtual ~Resume(){}
public:
virtual Resume * Clone() //复制方法 这是关键方法
{
return NULL;
}
virtual void SetName(char *str)=0;
virtual void SetExperients(char *str)=0;
virtual void Show()=0;
};
class WorkExperients //工作经历类
{
private:
char *workEx;
public:
WorkExperients(){}
virtual ~WorkExperients(){delete []workEx;}
public:
void SetWorkEx(char *str)
{
if(NULL == str)
{
this->workEx = new char[1];
this->workEx = "\0";
}
else
{
int len = strlen(str)+1;
this->workEx = new char[len];
strcpy(this->workEx , str);
}
}
void Show()
{
cout << this->workEx << endl;
}
char *GetWorkExperients() //获取工作经历
{
return this->workEx;
}
};
class ResumeA : public Resume
{
private:
WorkExperients *work;
public:
ResumeA(){}
ResumeA(const char *name) //实例化某个人名对应下的简历
{
if(NULL == name)
{
this->name = new char[1];
this->name = "\0";
}
else
{
int len = strlen(name)+1;
this->name = new char[len];
strcpy(this->name , name);
}
this->work = new WorkExperients(); //实例化时创建了工作经历类
}
///
ResumeA(ResumeA &resume) //拷贝构造函数中实现具体复制
{
int len = strlen(resume.name)+1;
this->name = new char[len];
strcpy(this->name , resume.name);
//复制工作经历
this->work = new WorkExperients(); //实例化一个用以从已有resume的工作经历对象复制到这个实例化的对象
this->work->SetWorkEx(resume.GetWorkEx()->GetWorkExperients());
}
Resume * Clone()
{
return new ResumeA(*this); //复制复制,就是把自己复制了传递给别人
}
///
WorkExperients *GetWorkEx()
{
return work;
}
virtual ~ResumeA()
{
delete []this->name;
}
void SetName(char *str)
{
this->name = str;
}
void SetExperients(char *str) //设置工作经历
{
work->SetWorkEx(str);
// work->Show();
}
void Show()
{
cout << "Resume Name is " << this->name << endl;
work->Show();
}
};
void main()
{
Resume *resume = new ResumeA("Sony");
resume->SetExperients("I have done job for 5 years");
resume->Show();
Resume *resumeDuplication = resume->Clone();
resumeDuplication->SetName("Monkey");
resumeDuplication->SetExperients("I have done job for 7 years");
resumeDuplication->Show();
//-----------用以检查工作经历对象是否是引用了同一个对象还是分别是两个不同的工作经历对象-------------
resume->Show();
// resume->SetExperients("I have done job for 5 years");
}