设计模式--原型模式Prototype(创建型)

时间:2023-03-09 03:55:16
设计模式--原型模式Prototype(创建型)

一、原型模式

用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。原型模式实现的关键就是实现Clone函数,还需要实现深拷贝。

二、UML类图

设计模式--原型模式Prototype(创建型)

三、例子

//父类
class Resume
{
protected:
char *name;
public:
Resume() {}
virtual ~Resume() {}
virtual Resume* Clone() { return NULL; }
virtual void Set(char *n) {}
virtual void Show() {}
}; class ResumeA : public Resume
{
public:
ResumeA(const char *str); //构造函数
ResumeA(const ResumeA &r); //拷贝构造函数
~ResumeA(); //析构函数
ResumeA* Clone(); //克隆,关键所在
void Show(); //显示内容
};
ResumeA::ResumeA(const char *str)
{
if(str == NULL) {
name = new char[];
name[] = '\0';
}
else {
name = new char[strlen(str)+];
strcpy(name, str);
}
}
ResumeA::~ResumeA() { delete [] name;}
ResumeA::ResumeA(const ResumeA &r) {
name = new char[strlen(r.name)+];
strcpy(name, r.name);
}
ResumeA* ResumeA::Clone() {
return new ResumeA(*this);
}
void ResumeA::Show() {
cout<<"ResumeA name : "<<name<<endl;
} int main()
{
Resume *r1 = new ResumeA("A");
Resume *r2 = new ResumeB("B");
Resume *r3 = r1->Clone();
Resume *r4 = r2->Clone();
r1->Show(); r2->Show();
//删除r1,r2
delete r1; delete r2;
r1 = r2 = NULL;
//深拷贝所以对r3,r4无影响
r3->Show(); r4->Show();
delete r3; delete r4;
r3 = r4 = NULL;
}

三、原型模式的优点及适用场景

使用原型模式创建对象比直接new一个对象在性能上要好的多,因为Object类的clone方法是一个本地方法,它直接操作内存中的二进制流,特别是复制大对象时,性能的差别非常明显。(性能提升?需要研究)

使用原型模式的另一个好处是简化对象的创建,使得创建对象就像我们在编辑文档时的复制粘贴一样简单。

因为以上优点,所以在需要重复地创建相似对象时可以考虑使用原型模式。比如需要在一个循环体内创建对象,假如对象创建过程比较复杂或者循环次数很多的话,使用原型模式不但可以简化创建过程,而且可以使系统的整体性能提高很多。