前序
這回小菜准備去應聘了,大鳥看了小菜的簡歷後感覺他都是在瞎扯.小菜准備了很多份相同的簡歷.於是大鳥便讓小菜同學通過編寫代碼來實現相同的三份簡歷.
不久後小菜實現了第一版的代碼.
小菜的第一版代碼
#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 ",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 ",name,sex,age);
printf("工作經歷:%s %s ",work->WorkDate(),work->Company());
}
virtual Resume* Clone()
{
Resume* Result = new Resume(work);
Result->name = name;
Result->sex = se