定义
备忘录模式(Memento Pattern)是一种行为设计模式,用于在不破坏对象封装性的前提下捕获并保存其内部状态,以便后续可恢复到该状态。通过隔离状态存储逻辑,实现对象状态的保存与回滚,降低原对象的职责。核心是为对象提供“后悔药”机制。
结构
适用场景
1)撤销/重做功能
文本编辑、图像处理软件中,用户操作可逆(如保存编辑步骤)。
2)游戏存档
保存角色状态(等级、装备、位置),支持中断后继续游戏。
3)事务回滚
数据库操作失败时,回滚到操作前的状态。
4)版本控制
代码版本管理(如Git),通过快照回溯历史版本。
使用示例
文本编辑器撤销功能。
/**
* 备忘录类
*/
public class EditorMemento {
private final String content;
public EditorMemento(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
/**
* 发起人类
*/
public class TextEditor {
private String content;
public void write(String text) {
content = text;
}
public EditorMemento save() {
return new EditorMemento(content);
}
public void restore(EditorMemento memento) {
content = memento.getContent();
}
public void print() {
System.out.println("当前内容:" + content);
}
}
/**
* 负责人类(历史记录管理)
*/
public class HistoryManager {
private Stack<EditorMemento> history = new Stack<>();
public void saveSnapshot(EditorMemento memento) {
history.push(memento);
}
public EditorMemento undo() {
return history.pop();
}
}
public class Client {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
HistoryManager history = new HistoryManager();
editor.write("第一版文本");
history.saveSnapshot(editor.save()); // 保存状态
editor.write("修改后的文本");
editor.print(); // 输出:修改后的文本
editor.restore(history.undo()); // 恢复到上一状态
editor.print(); // 输出:第一版文本
}
}