设计模式之原型模式
【定义】用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
【情景】假设现在在一家公司应聘,对方要求填写求职信息表,多位面试官每人都要一份,需要手工填写。现在有两种方式可供选择:a、手工填写多份信息表; 2、手工填写一份,然后剩下的拿填写完得第一份复印。第二种方式就是这里所说的原型模式,第一份手工填写的信息表就是一个原型。一般在初始化的信息不发生变化的情况下,克隆是最好的办法。这既隐藏了对象创建的细节,有对性能大大的提高。
【UML】
【代码】
#include <string.h>
#include <iostream>
using namespace std;
class Resume
{
protected:
char* name;
public:
Resume() {}
virtual Resume* Clone() { return NULL; }
virtual void SetName(char* name) {}
virtual void Show() {}
};
class ConcreteResumeA : public Resume
{
public:
ConcreteResumeA(char* name);
ConcreteResumeA(ConcreteResumeA &a);
~ConcreteResumeA();
void SetName(char* name);
Resume* Clone();
void Show();
};
ConcreteResumeA::ConcreteResumeA(char* name)
{
if(NULL == name)
{
this->name = new char[1];
this->name[0] = '\0';
}
else
{
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
}
ConcreteResumeA::ConcreteResumeA(ConcreteResumeA &a)
{
this->name = new char[strlen(a.name) + 1];
strcpy(name, a.name);
}
ConcreteResumeA::~ConcreteResumeA()
{
delete [] name;
}
void ConcreteResumeA::SetName(char* name)
{
delete [] this->name;
if(NULL == name)
{
this->name = new char[1];
this->name[0] = '\0';
}
else
{
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
}
void ConcreteResumeA::Show()
{
cout<<"ConcreteResumeA name: "<<name<<endl;
}
Resume* ConcreteResumeA::Clone()
{
return new ConcreteResumeA(*this);
}
int main()
{
Resume *a1 = new ConcreteResumeA("Resume A");
Resume *a2 = a1->Clone();
a1->Show();
delete a1;
a2->Show();
delete a2;
return 0;
}
不积跬步无以至千里,不积小流无以成江河。