备忘录模式在c++中用于不破坏封装地保存和恢复对象内部状态,核心角色为originator(创建/恢复状态)、memento(安全存储状态,仅originator可访问)和caretaker(管理备忘录但不可读写)。

备忘录模式(Memento Pattern)在 C++ 中用于在不破坏封装的前提下,捕获并外部化一个对象的内部状态,以便之后能恢复到该状态。它常用于实现撤销(Undo)、快照、回滚等机制。
核心角色与职责
要正确实现备忘录模式,需明确三个关键角色:
- Originator(发起人):创建一个备忘录来记录当前状态,并可从备忘录恢复状态;其内部状态是私有的,不对外暴露。
- Memento(备忘录):存储 Originator 的某个时刻的内部状态;通常为窄接口(只允许 Originator 访问,其他类不可修改或读取细节)。
- Caretaker(管理者):负责保存和管理多个 Memento 对象,但不能访问或修改其内容(即不能调用 Memento 的私有成员)。
典型 C++ 实现(带完整源码)
以下是一个简洁、安全、符合封装原则的 C++11+ 实现:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
#include <memory>
#include <vector>
<p>class Editor {
private:
std::string content_;
int cursor<em>pos</em>;</p><p>public:
Editor() : content_(""), cursor<em>pos</em>(0) {}</p><pre class='brush:php;toolbar:false;'>void type(const std::string& text) {
content_ += text;
cursor_pos_ += static_cast<int>(text.length());
}
void erase(int n) {
if (n > static_cast<int>(content_.length())) n = content_.length();
content_ = content_.substr(0, content_.length() - n);
cursor_pos_ = std::max(0, cursor_pos_ - n);
}
// 创建备忘录(返回值是友元类,仅 Editor 可构造/读取)
class Memento {
friend class Editor; // 关键:仅 Editor 可访问私有字段
private:
std::string content_;
int cursor_pos_;
Memento(const std::string& c, int pos) : content_(c), cursor_pos_(pos) {}
public:
// 提供只读访问(可选,若需 Caretaker 展示快照信息)
std::string getContent() const { return content_; }
int getCursorPos() const { return cursor_pos_; }
};
// 保存当前状态
std::unique_ptr<Memento> save() const {
return std::make_unique<Memento>(content_, cursor_pos_);
}
// 恢复指定状态
void restore(const Memento& m) {
content_ = m.content_;
cursor_pos_ = m.cursor_pos_;
}
void print() const {
std::cout << "[Editor] '" << content_ << "' | cursor=" << cursor_pos_ << "\n";
}};
// 管理器:只存、不看、不改 class History { private: std::vector<:unique>ptr<:memento>> snapshots;
public: void push(std::uniqueptr<:memento> m) { snapshots.push_back(std::move(m)); }
std::unique_ptr<Editor::Memento> pop() {
if (snapshots_.empty()) return nullptr;
auto last = std::move(snapshots_.back());
snapshots_.pop_back();
return last;
}
size_t size() const { return snapshots_.size(); }};
int main() { Editor editor; History history;
editor.type("Hello");
editor.print(); // [Editor] 'Hello' | cursor=5
history.push(editor.save()); // 保存第1个状态
editor.type(" World");
editor.print(); // [Editor] 'Hello World' | cursor=11
history.push(editor.save()); // 保存第2个状态
editor.erase(6);
editor.print(); // [Editor] 'Hello' | cursor=5 (已删掉" World")
if (auto m = history.pop()) {
editor.restore(*m); // 恢复到“Hello World”
editor.print(); // [Editor] 'Hello World' | cursor=11
}
return 0;}
关键设计要点说明
- 窄接口保护:Memento 类将构造函数和成员设为 private,并仅声明 Originator(Editor)为 friend,确保只有 Originator 能创建和读取状态,Caretaker(History)只能持有指针,无法窥探或篡改。
-
值语义 + 移动语义:使用
std::unique_ptr<memento></memento>管理备忘录生命周期,避免裸指针和深拷贝开销,也防止误共享。 - 无侵入式快照:save() 是 const 成员函数,不影响 Originator 当前行为;restore() 接收 const 引用,语义清晰安全。
- 支持多级撤销:History 使用 vector + unique_ptr,天然支持栈式 Undo/Redo(只需再加一个 redoStack 即可扩展)。
常见变体与注意事项
- 若需支持跨对象共享状态(如协同编辑),可将 Memento 设计为可序列化(添加 to_json()/from_json() 或 operator
- 内存敏感场景下,可对 Memento 做增量压缩(例如只存 diff)或引入自动清理策略(如限制最大快照数)。
- 避免把 Memento 写成纯数据结构(如 struct)并 public 所有字段——这会破坏封装,违背模式本意。
- C++ 中不推荐用嵌套 public class 暴露状态;friend + private 是更可控的选择。
基本上就这些。备忘录模式本身不复杂,但容易忽略封装边界——关键是让 Memento “看得见、摸不着”,靠 friend 和访问控制守住那条线。











