备忘录模式通过发起者保存状态、备忘录存储状态、管理者管理历史,实现对象状态的捕获与恢复,常用于撤销操作;示例中编辑器内容变更后可借助历史栈回退,核心在于封装性保护与深拷贝处理,需注意内存开销与生命周期控制。

备忘录模式(Memento Pattern)是一种行为型设计模式,用于在不破坏封装性的前提下捕获并保存对象的内部状态,以便在之后能将该对象恢复到原先的状态。它常用于实现撤销(Undo)功能、历史记录或事务回滚等场景。
备忘录模式包含三个主要角色:
下面是一个简单的 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 draft.");
history.push(editor.save()); // 保存状态
editor.setContent("Second draft.");
history.push(editor.save());
editor.setContent("Final 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++++如何实现备忘录设计模式_c++ Memento模式与状态撤销的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号