介绍
原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
核心:是提供一个clone方法,通过该方法进行对象的拷贝 。
优点: 性能优良 ; 逃避构造函数的约束
缺点:每个类都要重写有clone方法,对于以后的类需要全面的考虑所有成员的拷贝
应用:一个复杂对象多个修改者的场景,该对象应该具有自我复制功能,统一一套接口。 资源优化场景 、 性能和安全要求的场景
需要有抽象原型和具体原型,抽象原型只需要有虚析构函数和纯虚方法clone即可,有具体原型实现clone方法
注意:clone内的操作要深拷贝,对于指针等成员变量不能只copy指针
UML类图
简单示例:
#ifndef SIMPLE_PROTOTYPE_H
#define SIMPLE_PROTOTYPE_H
#include <iostream>
using namespace std;
/**
* @brief
* 简单的原型模式
*/
class Prototype
{
public:
virtual Prototype* Clone() = 0 ;
virtual void show() = 0;
};
class ConcretePrototype1 : public Prototype
{
public:
ConcretePrototype1()
{
m_name = "Prototype1";
m_age = 0;
}
ConcretePrototype1(string name , int age)
{
m_name = name;
m_age = age;
}
Prototype *Clone()
{
Prototype *temp = new ConcretePrototype1();
if (nullptr != temp )
return temp;
}
void show()
{
cout << "Name = "<<m_name<<" Age = "<<m_age<<endl;
}
private:
string m_name;
int m_age;
};
class ConcretePrototype2 : public Prototype
{
public:
ConcretePrototype2()
{
m_name = "Prototype2";
m_age = 1;
}
ConcretePrototype2(string name , int age)
{
m_name = name;
m_age = age;
}
Prototype *Clone()
{
Prototype *temp = new ConcretePrototype2(m_name , m_age);
if (nullptr != temp )
return temp;
}
void show()
{
cout << "Name = "<<m_name<<" Age = "<<m_age<<endl;
}
private:
string m_name;
int m_age;
};
#endif // SIMPLE_PROTOTYPE_H
调用:
Prototype *t1 = new ConcretePrototype1;
t1->show();
Prototype *t2 = t1->Clone();
t2->show();
Prototype *t3 = new ConcretePrototype2("聂风" , 38);
t3->show();
Prototype *t4 = t3->Clone();
t4->show();
欢迎各位大神在下方评论指导。随着以后对设计模式的认知加深,实时更新该文档。