备忘录模式 (Memento)
📖 通俗理解
玩游戏时的存档功能:
- 打 Boss 前先存个档
- 打输了,读档重来
- 游戏状态恢复到存档时刻
备忘录模式就是:在不破坏封装的前提下,保存对象的内部状态,以便之后恢复。
🎯 解决什么问题?
- 实现撤销/恢复功能
- 保存对象的历史状态
🌰 生活中的例子
- 游戏存档
- Ctrl + Z 撤销
- 数据库事务回滚
- 浏览器后退按钮
💻 Java 代码实现
场景:文本编辑器撤销
/**
* 备忘录:保存编辑器状态
*/
public class EditorMemento {
private final String content;
private final int cursorPosition;
public EditorMemento(String content, int cursorPosition) {
this.content = content;
this.cursorPosition = cursorPosition;
}
public String getContent() {
return content;
}
public int getCursorPosition() {
return cursorPosition;
}
}
/**
* 发起人:文本编辑器
*/
public class TextEditor {
private String content = "";
private int cursorPosition = 0;
public void type(String text) {
content += text;
cursorPosition = content.length();
System.out.println("输入: " + text);
}
public void display() {
System.out.println("内容: " + content);
System.out.println("光标位置: " + cursorPosition);
}
// 创建备忘录
public EditorMemento save() {
System.out.println("保存状态...");
return new EditorMemento(content, cursorPosition);
}
// 恢复状态
public void restore(EditorMemento memento) {
content = memento.getContent();
cursorPosition = memento.getCursorPosition();
System.out.println("恢复状态...");
}
}
/**
* 管理者:历史记录
*/
public class History {
private Stack<EditorMemento> history = new Stack<>();
public void push(EditorMemento memento) {
history.push(memento);
}
public EditorMemento pop() {
if (!history.isEmpty()) {
return history.pop();
}
return null;
}
}
使用:
public class Client {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
History history = new History();
// 输入并保存
editor.type("Hello ");
history.push(editor.save());
editor.type("World");
history.push(editor.save());
editor.type("!!!");
System.out.println("\n当前状态:");
editor.display();
// 撤销
System.out.println("\n执行撤销:");
editor.restore(history.pop());
editor.display();
System.out.println("\n再次撤销:");
editor.restore(history.pop());
editor.display();
}
}
输出:
输入: Hello
保存状态...
输入: World
保存状态...
输入: !!!
当前状态:
内容: Hello World!!!
光标位置: 14
执行撤销:
恢复状态...
内容: Hello World
光标位置: 11
再次撤销:
恢复状态...
内容: Hello
光标位置: 6
✅ 适用场景
- 需要保存和恢复对象状态
- 实现撤销/重做功能
- 需要保存历史快照
⚠️ 注意
频繁保存状态会消耗较多内存,可以考虑只保存增量。
小结
备忘录模式:保存对象状态,支持恢复。
三个角色:
- Originator(发起人):创建和恢复备忘录
- Memento(备忘录):存储状态
- Caretaker(管理者):保管备忘录
👉 下一篇:观察者模式
