当前位置: 首页 > news >正文

【设计模式】备忘录模式

概念

行为模式


类图

Memento


代码

#include <iostream>using namespace std;class Snapshot;
class Editor {
public:void SetText(const string& t) {text = t;}void SetCursor(int x, int y) {this->curX = x;this->curY = y;}void SetSelectionWidth(int width) {selectionWidth = width;}Snapshot* CreateSnapshot(const string& t, int x, int y, int w) {cout << "Create Snapshot." << endl;return nullptr;// return new Snapshot(this, t, x, y, w); // cannot implement in one cpp file}private:string text;int curX{}, curY{};int selectionWidth{};
};class Snapshot {
public:Snapshot(Editor* e, const string& t, int x, int y, int w) {editor = e;text = t;curX = x;curY = y;selectionWidth = w;};void Restore() {cout << "Restore from snapshot." << endl;editor->SetText(text);editor->SetCursor(curX, curY);editor->SetSelectionWidth(selectionWidth);}private:Editor* editor;string text;int curX, curY;int selectionWidth;
};class Command {
public:void MakeBackup(Editor* editor, const string& t, int x, int y, int w) {backup = editor->CreateSnapshot(t, x, y, w);}void Undo() {if (backup != nullptr) {backup->Restore();}}private:Snapshot* backup;
};int main(int argc, char *argv[]) {auto editor = new Editor();auto command = new Command();command->MakeBackup(editor, "Older State", 1, 2, 3);editor->SetText("Newer State");editor->SetCursor(2, 3);command->Undo();delete command;delete editor;return 0;
}
http://www.dtcms.com/a/394348.html

相关文章:

  • STM32_07_按键
  • 基于迁移学习和SqueezeNet的滚动轴承故障诊断(MATLAB)
  • 实战项目(十二:《AI画质增强与LED驱动控制:一场关于‘创造’与‘还原’的对话》):从LED冬奥会、奥运会及春晚等大屏,到手机小屏,快来挖一挖里面都有什么
  • 开发避坑指南(52):IDEA 2025.1.3 顶部显示类完整路径的设置方法
  • 安装Qt新之后出现两本帮助手册
  • Rust_2025:阶段1:day7.2unsafe , 链接相关
  • 【论文速递】2025年第15周(Apr-06-12)(Robotics/Embodied AI/LLM)
  • 设计模式简单说明:责任链与规则树
  • 自动备份脚本 mysql_hourly_backup.sh
  • SuperGLUE:自然语言理解的挑战与进步
  • 线程安全的单例模式、自旋锁,以及读者写者问题
  • U盘长期插在电脑上的影响
  • Windows 系统部署 PaddleOCR —— 基于 EPGF 架构
  • 数据一致性指的是什么?如何实现数据一致性?
  • 初识消息队列的世界
  • Python快速入门专业版(三十八):Python字典:键值对结构的增删改查与进阶用法
  • SpringCloudOAuth2+JWT:微服务统⼀认证方案
  • LeetCode 分类刷题:2517. 礼盒的最大甜蜜度
  • 深度学习优化器进阶:从SGD到AdamW,不同优化器的适用场景
  • C++ 之 【C++的IO流】
  • truffle学习笔记
  • 现代循环神经网络
  • vlc播放NV12原始视频数据
  • ThinkPHP8学习篇(七):数据库(三)
  • 链家租房数据爬虫与可视化项目 Python Scrapy+Django+Vue 租房数据分析可视化 机器学习 预测算法 聚类算法✅
  • MQTT协议知识点总结
  • C++ 类和对象·其一
  • TypeScript里的类型声明文件
  • 【LeetCode - 每日1题】设计电影租借系统
  • Java进阶教程,全面剖析Java多线程编程,线程安全,笔记12