Skip to content

备忘录模式

意图

在不破坏封装的前提下,捕获对象的内部状态并在对象之外保存,以便稍后恢复

类图

Java 示例

java
public class EditorMemento {
    private final String text;
    public EditorMemento(String text) { this.text = text; }
    public String getText() { return text; }
}

public class Editor {
    private String text = "";
    public void type(String s) { text += s; }
    public EditorMemento save() { return new EditorMemento(text); }
    public void restore(EditorMemento m) { this.text = m.getText(); }
    public String getText() { return text; }
}

public class History {
    private final java.util.Deque<EditorMemento> stack = new java.util.ArrayDeque<>();
    public void push(EditorMemento m) { stack.push(m); }
    public EditorMemento pop() { return stack.pop(); }
}

文本编辑器撤销、游戏存档均为典型场景。注意 备忘录大小 与深拷贝成本。

下一节:观察者模式