
优点 | 缺点 |
|---|---|
1. 状态封装:不暴露对象内部细节。 | 1. 内存占用高:频繁保存大对象状态可能导致内存溢出。 |
2. 简化原发器:状态管理职责分离。 | 2. 性能开销:频繁序列化/反序列化可能影响性能。 |
3. 支持状态回滚:灵活实现撤销/恢复。 | 3. 需管理生命周期:过期的备忘录需及时清理。 |
/**
* 备忘录类:保存文本编辑器的状态(文本内容和光标位置)
* 设为原发器的内部类,确保状态访问的封装性。
*/
public class TextEditor {
// 原发器状态
private String text;
private int cursorPosition;
public TextEditor() {
this.text = "";
this.cursorPosition = 0;
}
// 修改文本内容
public void write(String newText) {
this.text += newText;
this.cursorPosition += newText.length();
}
// 创建备忘录(保存当前状态)
public TextMemento save() {
return new TextMemento(text, cursorPosition);
}
// 从备忘录恢复状态
public void restore(TextMemento memento) {
this.text = memento.getText();
this.cursorPosition = memento.getCursorPosition();
}
// 打印当前状态
public void printStatus() {
System.out.printf("文本内容:%s\n光标位置:%d%n", text, cursorPosition);
}
/**
* 备忘录内部类:封装原发器的状态
*/
public static class TextMemento {
private final String text;
private final int cursorPosition;
// 仅允许原发器创建备忘录
private TextMemento(String text, int cursorPosition) {
this.text = text;
this.cursorPosition = cursorPosition;
}
// 仅允许原发器访问状态
private String getText() {
return text;
}
private int getCursorPosition() {
return cursorPosition;
}
}
}import java.util.Stack;
/**
* 负责人类:管理备忘录的历史记录(使用栈结构支持撤销操作)
*/
public class History {
private final Stack<TextEditor.TextMemento> mementos = new Stack<>();
// 保存状态
public void push(TextEditor.TextMemento memento) {
mementos.push(memento);
}
// 撤销操作(恢复上一次状态)
public TextEditor.TextMemento pop() {
if (mementos.isEmpty()) {
throw new IllegalStateException("无历史记录可撤销");
}
return mementos.pop();
}
}public class Client {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
History history = new History();
// 编辑文本并保存状态
editor.write("Hello");
history.push(editor.save());
editor.printStatus();
editor.write(" World!");
history.push(editor.save());
editor.printStatus();
// 撤销到上一次状态
System.out.println("\n===== 执行撤销 =====");
editor.restore(history.pop());
editor.printStatus();
// 再次撤销(无历史记录)
try {
editor.restore(history.pop());
} catch (IllegalStateException e) {
System.out.println("错误:" + e.getMessage());
}
}
}文本内容:Hello
光标位置:5
文本内容:Hello World!
光标位置:11
===== 执行撤销 =====
文本内容:Hello
光标位置:5
错误:无历史记录可撤销+----------------+ +----------------+
| Originator | <>-----+ | Memento |
+----------------+ +----------------+
| +createMemento() | -state |
| +restore(Memento) +----------------+
+----------------+ ^
| |
| |
+----------------+ +----------------+
| Caretaker | | |
+----------------+ +----------------+
| -mementos:List | | |
| +saveMemento() | | |
| +getMemento() | | |
+----------------+ +----------------+备忘录模式在 Java 生态中的典型应用包括:
UndoManager 管理编辑操作的撤销/重做。
掌握该模式能有效增强系统的可靠性和用户体验,尤其在需要状态回溯的场景中。