原型模式

一、什么是原型模式
1. 简介
原型模式类似于工厂模式,同样也提供了隔离对象与使用者之间的耦合关系,绕开了new的过程,但是需要这些具体的对象有稳定的接口。
原型模式采用克隆的方式动态的创建拥有某些具有稳定接口的新对象,使用的方法只需要注册一个原型对象,并且在需要此类对象的时候进行clone即可。

2. 应用场景
原型模式的设计目的有:利用拷贝替换构造对象,提升效率;避免了重复new相同对象的操作。

3. 结构图

如上图所示,原型模式的思想就是从一个现有对象中定义一个相同的对象,而略过了该对象的具体实现细节,隔离了使用者与产品对象的创建过程。

4. 代码示例

/*Prototype原型基类*/
class Prototype
{
protected:
    Prototype();
public:
    virtual Prototype* Clone() const=0; //定义Clone接口
    virtual ~Prototype();
};

class MyPrototype:public Prototype
{
public:
    MyPrototype();
    virtual ~MyPrototype();

    MyPrototype(const MyPrototype&);
    virtual Prototype* Clone() const;//实现基类定义的Clone接口,内部调用拷贝构造函数实现复制功能
};

#endif

#include "Prototype.h"
#include "iostream"

using namespace std;

////Prototype
Prototype::Prototype()
{
    cout<<"Prototype"<<endl;
}

Prototype::~Prototype()
{
    cout<<"~Prototype"<<endl;
}

//MyPrototype
MyPrototype::MyPrototype()
    : Prototype()
{
    cout<<"MyPrototype"<<endl;
}

MyPrototype::~MyPrototype()
{
    cout<<"~MyPrototype"<<endl;
}

MyPrototype::MyPrototype(const MyPrototype& cp)
{
    cout<<"MyPrototype copy"<<endl;
}

Prototype* MyPrototype::Clone() const
{
    return new MyPrototype(*this);
}
#include "Prototype.h"
#include <iostream>
using namespace std;

int main()
{
    Prototype* p1 = new MyPrototype();
    Prototype* clone1 = p1->Clone();

    delete p1;
    delete clone1;

    return 0;
}
原文地址:https://www.cnblogs.com/yuemw/p/10081203.html