备忘录模式通过发起者、备忘录和管理者三者协作,实现对象状态的保存与恢复。发起者负责创建和恢复状态,备忘录存储状态且对外只读,管理者保存多个备忘录以支持撤销操作。示例中Editor为发起者,Memento保存文本状态,History用栈管理备忘录,实现撤销功能。该模式保持封装性,适用于实现撤销、快照等场景,需注意内存消耗与状态一致性。

在C++中,备忘录模式(Memento Pattern)是一种行为设计模式,用于在不破坏封装性的前提下,保存和恢复对象的内部状态。这种模式特别适用于实现撤销功能、快照保存或状态回滚。
该模式包含三个主要角色:
下面是一个简洁的C++示例,展示如何使用备忘录模式保存和恢复对象状态:
#include <iostream>
#include <string>
#include <stack>
// 备忘录类:保存状态
class Memento {
std::string state;
public:
Memento(const std::string& s) : state(s) {}
const std::string& getState() const { return state; }
};
// 发起者类:管理自身状态
class Editor {
std::string content;
public:
void setContent(const std::string& text) {
content = text;
}
std::string getContent() const {
return content;
}
// 创建备忘录(保存当前状态)
Memento save() const {
return Memento(content);
}
// 从备忘录恢复状态
void restore(const Memento& m) {
content = m.getState();
}
};
// 管理者类:保存多个备忘录(例如用于撤销)
class History {
std::stack<Memento> states;
public:
void push(const Memento& m) {
states.push(m);
}
Memento pop() {
if (states.empty()) {
throw std::runtime_error("No saved states");
}
Memento m = states.top();
states.pop();
return m;
}
bool empty() const {
return states.empty();
}
};
通过组合上述类,可以轻松实现文本编辑器的撤销操作:
立即学习“C++免费学习笔记(深入)”;
int main() {
Editor editor;
History history;
editor.setContent("First version");
history.push(editor.save()); // 保存状态
editor.setContent("Second version");
history.push(editor.save()); // 保存状态
editor.setContent("Third version");
std::cout << "Current: " << editor.getContent() << "\n";
// 撤销一次
if (!history.empty()) {
editor.restore(history.pop());
std::cout << "After undo: " << editor.getContent() << "\n";
}
// 再次撤销
if (!history.empty()) {
editor.restore(history.pop());
std::cout << "After second undo: " << editor.getContent() << "\n";
}
return 0;
}
使用备忘录模式时需要注意以下几点:
基本上就这些。备忘录模式通过分离状态存储与管理逻辑,使对象具备“后悔”能力,是实现撤销、重做、快照等功能的优雅方式。
以上就是C++备忘录模式 对象状态保存恢复的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号