原型模式
前序
这回小菜准备去应聘了,大鸟看了小菜的简历后感觉他都是在瞎扯.小菜准备了很多份相同的简历.于是大鸟便让小菜同学通过编写代码来实现相同的三份简历.
不久后小菜实现了第一版的代码.
小菜的第一版代码
#include <stdio.h>
class Resume
{
public:
Resume(char* _name) : name(_name),sex(0),age(0),timeArea(0),company(0){}
void SetPersonalInfo(char* _sex,char* _age)
{
sex = _sex;
age = _age;
}
void SetWorkExperience(char* _timeArea,char* _company)
{
timeArea = _timeArea;
company = _company;
}
void Display()
{
printf("%s %s %s\n",name,sex,age);
printf("工作经历:%s %s",timeArea,company);
}
protected:
char* name;
char* sex;
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* _sex,char* _age)
{
sex = _sex;
age = _age;
}
void SetWorkExperience(char* _workDate,char* _company)
{
work->WorkDate() = _workDate;
work->Company() = _company;
}
void Display()
{
printf("%s %s %s\n",name,sex,age);
printf("工作经历:%s %s\n",work->WorkDate(),work->Company());
}
virtual Resume* Clone()
{
Resume* Result = new Resume(work);
Result->name = name;
Result->sex = sex;
Result->age = age;
return Result;
}
protected:
Resume(WorkExperience* _work)
{
work = _work->Clone();
}
char* name;
char* sex;
char* age;
WorkExperience* work;
};
int main()
{
Resume* a = new Resume("大鸟");
a->SetPersonalInfo("男","29");
a->SetWorkExperience("1998-2000","XX公司");
Resume* b = a->Clone();
b->SetWorkExperience("1998-2006","YY企业");
Resume* c = a->Clone();
c->SetPersonalInfo("男","24");
c->SetWorkExperience("1998-2003","ZZ企业");
a->Display();
b->Display();
c->Display();
delete a;
delete b;
delete c;
return 0;
}
运行结果
所有文件打包下载
posted on 2011-05-12 16:20
lwch 阅读(1995)
评论(1) 编辑 收藏 引用 所属分类:
设计模式