原型模式(Prototype)
注:給出題目,首先能做的可能是先寫出一個原始的方法的簡單版本,然後再根據對設計模式的理解,按照對應設計模式來修改源代碼。
1. 原型模式:
其實就是深拷貝與淺拷貝的實現。
2. 複製簡歷的代碼實例:
第一版本代碼:
class Resume
{
private:
string name;
string sex;
unsigned int age;
string time;
string company;
public:
Resume(string n)
{
name=n;
}
//設置個人信息
void SetPersonalInfo(string s,unsigned int a)
{
this->sex=s;
this->age=a;
}
void SetWorkExperience(string t,string com)
{
this->time=t;
this->company=com;
}
void display()
{
cout<<name<<":"<<sex<<" "<<age<<endl;
cout<<"工作經歷:"<<time<<" "<<company<<endl;
}
};
int main()
{
Resume *a=new Resume("大鳥");
a->SetPersonalInfo("nan",29);
a->SetWorkExperience("1998-2000","XX公司");
Resume *b=a;
Resume *c=a;
a->display();
b->display();
c->display();
return 0;
}
第二版代碼---原型模式:
class Resume
{
private:
string name,sex,age,timeArea,company;
public:
Resume(string s)
{
name=s;
}
void setPersonalInfo(string s,string a)
{
sex=s;
age=a;
}
void setWorkExperience(string t,string c)
{
timeArea=t;
company=c;
}
void display()
{
cout<<name<<" "<<sex<<" "<<age<<endl;
cout<<"工作經歷: "<<timeArea<<" "<<company<<endl<<endl;
}
Resume *clone()
{
Resume *b;
b=new Resume(name);
b->setPersonalInfo(sex,age);
b->setWorkExperience(timeArea,company);
return b;
}
};
int main()
{
Resume *r=new Resume("李俊宏");
r->setPersonalInfo("男","26");
r->setWorkExperience("2007-2010","讀研究生");
r->display();
Resume *r2=r->clone();
r2->setWorkExperience("2003-2007","讀本科");
r->display();
r2->display();
return 0;
}