备忘录模式
Memento — 在不破坏封装的前提下,保存和恢复对象的历史状态
一句话理解
给对象拍一个快照,需要时可以恢复到之前的状态。就像游戏存档 / 读档。
解决什么问题
- 需要实现"撤销"功能,但不想暴露对象的内部细节
- 保存历史状态以便回滚
怎么写
// 备忘录:保存状态的快照
public class Memento {
private final String state;
public Memento(String state) { this.state = state; }
public String getState() { return state; }
}
// 原发器:需要被保存状态的对象
public class Editor {
private String content = "";
public void type(String text) { content += text; }
public String getContent() { return content; }
// 保存当前状态
public Memento save() { return new Memento(content); }
// 恢复到某个状态
public void restore(Memento m) { content = m.getState(); }
}
// 管理者:管理备忘录的历史
public class History {
private final Stack<Memento> stack = new Stack<>();
public void push(Memento m) { stack.push(m); }
public Memento pop() { return stack.pop(); }
}Editor editor = new Editor();
History history = new History();
editor.type("Hello ");
history.push(editor.save()); // 存档
editor.type("World");
history.push(editor.save()); // 存档
editor.type("!!!");
System.out.println(editor.getContent()); // Hello World!!!
editor.restore(history.pop());
System.out.println(editor.getContent()); // Hello World
editor.restore(history.pop());
System.out.println(editor.getContent()); // Hello使用场景
- 文本编辑器的 undo/redo
- 游戏存档/读档
- 浏览器的前进/后退
- 数据库事务的回滚点(Savepoint)
- 版本控制系统(Git 的每个 commit 就是一个快照)