设计模式:原型模式(C++)

概述

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

类图

<<interface>> Prototype Prototype* clone() Person Person* clone() Animal Animal* clone()

以下为 C++ 代码原型的实现方式,与其他(PHP、Java)等不同。例:

cpp 复制代码
class Prototype {
public:
    ~Prototype() {}
    virtual Prototype* clone() = 0;
}
class Person : public Prototype {
    Person* clone() {
        return new Person(*this);
    }
}
class Animal : public Prototype {    
    Animal* clone() {
        return new Animal(*this);
    }
}

C++ 代码,父类 Prototype 通过纯虚函数 clone() 进行派生类对象的复制。父类中 clone() 函数的返回值为Prototype*,而子类为 Person*Animal*,利用了 C++ 的协变特性。

c++ 复制代码
Prototype* p = new Person();
// 此返回值为 Prototype*
p->clone();

Person* p2 = new Person();
// 此返回值为 Person*
p2->clone();
相关推荐
wuminyu16 分钟前
JUC组件逐层剥离与深度剖析
java·linux·c语言·jvm·c++·算法
独隅1 小时前
CLion 接入 Codex 的完整配置使用全面指南
c++·ide·ai·c++23
老洋葱Mr_Onion1 小时前
【C++】高精度模板
开发语言·c++·算法
梓仁沐白1 小时前
【Agent 设计模式】推理技术
设计模式
Kinghiee2 小时前
从使用场景切入前端常见设计模式
前端·设计模式
我不是懒洋洋3 小时前
从零实现一个分布式计算:MapReduce的核心设计
c++
小王C语言13 小时前
【7. 实现登录注册模块】:实现会话管理、注册/登录/退出 API
网络·c++
峥无15 小时前
C++11 深度详解:现代 C++ 基石全梳理
开发语言·c++·笔记
阿米亚波15 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl
小王C语言16 小时前
【3. 基于 Vibe Coding 的 OJ 平台】. 构建仓库、环境准备、需求梳理、安装依赖
网络·c++