设计模式:原型模式(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();
相关推荐
C^h9 小时前
c++ string
开发语言·c++
raindayinrain10 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的10 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao10 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
小徐不徐说11 小时前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
大都督会赢的11 小时前
C++第一节课
开发语言·c++
UIU11411 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
TMedical12 小时前
MedPlanning 截骨模拟矫形功能
c++·图像处理·人工智能·qt·健康医疗
qq_4069810312 小时前
共享变量一 关于extern与const
开发语言·c++
chari克里14 小时前
QT5.15.2 + msvc2022部署全流程说明(windows可联网环境)
开发语言·c++·qt