原型模式
前序
这回小菜准备去应聘了,大鸟看了小菜的简历后感觉他都是在瞎扯.小菜准备了很多份相同的简历.于是大鸟便让小菜同学通过编写代码来实现相同的三份简历.不久后小菜实现了第一版的代码.
小菜的第一版代码
#include <stdio.h>
class Resume
{
public:
Resume(char* _name) : name(_name),易做图(0),age(0),timeArea(0),company(0){}
void SetPersonalInfo(char* _易做图,char* _age)
{
易做图 = _易做图;
age = _age;
}
void SetWorkExperience(char* _timeArea,char* _company)
{
timeArea = _timeArea;
company = _company;
}
void Display()
{
printf("%s %s %s ",name,易做图,age);
printf("工作经历:%s %s",timeArea,company);
}
protected:
char* name;
char* 易做图;
char* age;
char* timeArea;
char* company;
};
int main()
{
Resume a("大鸟");
a.SetPersonalInfo("男","29");
a.SetWorkExperience("1998-2000","XX公司");
Resume b("大鸟");
b.SetPersonalInfo("男","29");
b.SetWorkExperience("1998-2000","XX公司");
Resume c("大鸟");
c.SetPersonalInfo("男","29");
c.SetWorkExperience("1998-2000","XX公司");
a.Display();
b.Display();
c.Display();
return 0;
}
大鸟看后说到:”三份简历需要三次初始化,这样客户端的代码很麻烦,如果要二十份那就要二十次初始化.”
小菜答到:”是的.如果写错了一个字那就要改二十次.”
于是大鸟便叫小菜用原型模式重写了一遍代码.
原型模式
通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。实现方式(UML类图)
实现代码
#include <stdio.h>
class ICloneable
{
public:
virtual ICloneable* Clone()=0;
};
// 工作经历
class WorkExperience : public ICloneable
{
public:
char*& WorkDate()
{
return workDate;
}
char*& Company()
{
return company;
}
virtual WorkExperience* Clone()
{
WorkExperience* Result = new WorkExperience();
Result->WorkDate() = workDate;
Result->Company() = company;
return Result;
}
protected:
char* workDate;
char* company;
};
// 简历
class Resume : public ICloneable
{
public:
Resume(char* _name) : name(_name),work(new WorkExperience()){}
~Resume()
{
delete work;
}
void SetPersonalInfo(char* _易做图,char* _age)
{
易做图 = _易做图;
age = _age;
}
void SetWorkExperience(char* _workDate,char* _company)
{
work->WorkDate() = _workDate;
work->Company() = _company;
}
void Display()
{
printf("%s %s %s ",name,易做图,age);
printf("工作经历:%s %s ",work->WorkDate(),work->Company());
}
virtual Resume* Clone()
{
Resume* Result = new Resume(work);
Result->name = name;
Result->易做图 = se
补充:软件开发 , C语言 ,