设计模式:原型模式(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();
相关推荐
_F_y1 天前
MySQL用C/C++连接
c语言·c++·mysql
兩尛1 天前
c++知识点2
开发语言·c++
xiaoye-duck1 天前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Azure_withyou1 天前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月1 天前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
L_09071 天前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
智者知已应修善业1 天前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德1 天前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
diediedei1 天前
模板编译期类型检查
开发语言·c++·算法
mmz12071 天前
分治算法(c++)
c++·算法