设计模式:原型模式(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();
相关推荐
zhaoshuzhaoshu31 分钟前
设计模式之行为型设计模式详解
python·设计模式
yong15858553431 小时前
Linux C++ 中的 volatile变量在多线程环境下进行运算的问题
c语言·c++
小肝一下1 小时前
c++从入门到跑路——string类
开发语言·c++·职场和发展·string类
楼田莉子1 小时前
设计模式:构造器模式
开发语言·c++·后端·学习·设计模式
邪修king1 小时前
UE5 零基础入门第二弹:让你的几何体 “活” 起来 ——Actor 基础与蓝图交互入门
c++·ue5·交互
玉树临风ives1 小时前
atcoder ABC 453 题解
数据结构·c++·算法·图论·atcoder
小则又沐风a1 小时前
STL库: string类
开发语言·c++
mmz12071 小时前
深度优先搜索DFS2(c++)
c++·算法·深度优先
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 169. 多数元素 | C++ 哈希表基础解法
c++·leetcode·散列表
暴力求解1 小时前
C++ ---string类(三)
开发语言·c++