设计模式(十二):原型模式(持续更新。。。)
定义:
·是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式
主要解决:
·在运行期建立和删除原型。
如何解决:
·利用已有的一个原型对象,快速地生成和原型对象一样的实例。
以代码为例:
类图关系如下
一、定义Prototype类
声明一个接口来克隆自己
#include <iostream>
#include <string>
class Prototype
{
public:
virtual ~Prototype() {}
virtual Prototype* clone() = 0;
virtual std::string type() = 0;
// ...*
};
二、声明Prototype的实现类A、B。
实现克隆自身的操作
class ConcretePrototypeA : public Prototype
{
public:
~ConcretePrototypeA() {}
Prototype* clone()
{
return new ConcretePrototypeA();
}
std::string type()
{
return "type A";
}
// ...
};
class ConcretePrototypeB : public Prototype
{
public:
~ConcretePrototypeB() {}
Prototype* clone()
{
return new ConcretePrototypeB();
}
std::string type()
{
return "type B";
}
// ...
};
三、声明client类
通过要求原型克隆自己来创建一个新对象
class Client
{
public:
static void init()
{
types[ 0 ] = new ConcretePrototypeA();
types[ 1 ] = new ConcretePrototypeB();
}
static void remove()
{
delete types[ 0 ];
delete types[ 1 ];
}
static Prototype* make( const int index )
{
if ( index >= n_types )
{
return nullptr;
}
return types[ index ]->clone();
}
// ...
private:
static Prototype* types[ 2 ];//声明Prototype类成员为静态变量
static int n_types;
};
Prototype* Client::types[ 2 ];
int Client::n_types = 2;
四、main函数调用
int main()
{
Client::init();
Prototype *prototype1 = Client::make( 0 );
std::cout << "Prototype: " << prototype1->type() << std::endl;
delete prototype1;
Prototype *prototype2 = Client::make( 1 );
std::cout << "Prototype: " << prototype2->type() << std::endl;
delete prototype2;
Client::remove();
return 0;
}
运行结果
Prototype: type A
Prototype: type B
这样就实现了一个简单的原型模式
原型模式的优缺点
优点:
1、性能提高
2、逃避构造函数的约束。
缺点:
1、配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
2、必须实现 Clone接口。