创建型模式 | 原型模式

一、原型模式

1、原理

原型模式,用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。原型像是一个模板,可以基于它复制好多对象,而复制出来的副本产生任何变化都不会影响到原型(注意:前提是clone的实现要满足深拷贝)。

2、UML类图

要实现原型模式,关键就是要实现原型接口里面的Clone方法,通过Clone方法来产生原型对象的副本,如下:

3、示例

声明一个IShape接口,该接口核心的是Clone方法。分别两个实现类CircleSquare,都实现了接口里面的方法,然后分别创建两个实现类对应的实例,并通过Clone方法产生实例的副本,如下:

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

// IShape 接口类
class IShape
{
public:
    virtual string GetShapeName() = 0;
    virtual void SetShapeName(string &) = 0;
    virtual IShape* Clone() = 0;
};

// Square 类
class Square : public IShape
{
private:
    string m_shapeName;

public:
    Square(string &shapeName) : m_shapeName(shapeName){}
    string GetShapeName()
    {
        return m_shapeName;
    }
    void SetShapeName(string &str)
    {
        m_shapeName = str;
    }
    IShape* Clone()
    {
        return new Square(this->m_shapeName);
    }
};

// Circle 类
class Circle : public IShape
{
private:
    string m_shapeName;

public:
    Circle(string &shapeName) : m_shapeName(shapeName){}
    string GetShapeName()
    {
        return m_shapeName;
    }
    void SetShapeName(string &str)
    {
        m_shapeName = str;
    }
    IShape* Clone()
    {
        return new Circle(this->m_shapeName);
    }
};

int main()
{
    string str1 = "Square";
    string str2 = "Circle";

    IShape *pShape1 = new Square(str1);
    IShape *pShape2 = new Circle(str2);

    IShape *pClone1 = pShape1->Clone();
    IShape *pClone2 = pShape2->Clone();

    cout << "pClone1 name : " << pClone1->GetShapeName() << endl;
    cout << "pClone2 name : " << pClone2->GetShapeName() << endl;

    return 0;
}

4、总结

使用原型模式隐藏了对象创建的细节,不论对象多么的复杂,使用者调用Clone接口就可以创建一个原型对象的副本。同时无需初始化,可动态地获取当前原型的状态(即:如果修改了原型对象,在修改后调用Clone方法,获取到的依然是原型对象的最新副本),并在当前基础上进行拷贝。

相关推荐
艾伦野鸽ggg8 分钟前
JavaScript 原型链与原型对象详解
javascript·原型模式
AgentMaster2 小时前
元数据、血缘、质量、安全四大模块能力拆解,数据治理方案对比:4 种技术路线深度评测
大数据·数据库·数据仓库·人工智能·原型模式
码匠许师傅1 天前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml
小程故事多_801 天前
从快速迭代到稳定存续,Google五大设计模式重构长效AI智能体落地逻辑
人工智能·设计模式·重构
码匠许师傅2 天前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式
2401_868534782 天前
网规备考_2.4 路由协议
c++·设计模式
cpp_learner2 天前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅2 天前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
新知图书3 天前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头3 天前
39面向对象(高级)-设计模式
java·开发语言·设计模式