(一)创建型设计模式:4、原型模式(Prototype Pattern)

目录

1、原型模式的含义

2、C++实现原型模式的简单实例


1、原型模式的含义

通过复制现有对象来创建新对象,而无需依赖于显式的构造函数或工厂方法,同时又能保证性能。

The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to: avoid subclasses of an object creator in the client application, like the factory method pattern does.

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

(使用原型实例指定将要创建的对象类型,通过复制这个实例创建新的对象。)

2、C++实现原型模式的简单实例

cpp 复制代码
#include <iostream>
#include <string>

// 抽象原型类
class Prototype {
public:
    virtual Prototype* clone() const = 0;
    virtual void show() const = 0;
};

// 具体原型类
class ConcretePrototype : public Prototype {
public:
    ConcretePrototype(const std::string& name) : m_name(name) {}

    Prototype* clone() const override {
        return new ConcretePrototype(*this);
    }

    void show() const override {
        std::cout << "ConcretePrototype: " << m_name << std::endl;
    }

private:
    std::string m_name;
};

int main() {
    // 创建原型对象

    Prototype* prototype = new ConcretePrototype("Prototype");

    // 克隆原型对象

    Prototype* clone = prototype->clone();

    // 展示原型和克隆对象

    prototype->show();
    clone->show();

    delete prototype;
    delete clone;

    return 0;
}

在上述示例中,我们定义了一个抽象原型类(Prototype),其中包含了两个纯虚函数:clone()用于克隆对象,show()用于展示对象。然后,我们实现了具体的原型类(ConcretePrototype),它继承自抽象原型类,并实现了抽象原型类中的纯虚函数。

在主函数中,我们首先创建一个原型对象(ConcretePrototype),然后通过调用clone()方法来克隆原型对象,得到一个新的对象。最后,我们分别展示原型对象和克隆对象的信息。

相关推荐
咖啡八杯1 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
玖玥拾2 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you3 小时前
constexpr函数
c++
凡人叶枫3 小时前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫4 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss4 小时前
BRpc使用
c++·rpc
-森屿安年-4 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream4 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G4 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天20224 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++