23种设计模式中的备忘录模式

67 阅读2分钟

在不破坏封装的前提下,捕获一个对象的内部状态,并允许在对象之外保存和恢复这些状态。

备忘录模式,主要用于捕获并保存一个对象的内部状态,以便将来可以恢复到该状态。

备忘录的模式主要由三个角色来实现:备忘录、发起人和管理员。

  • 备忘录(Memento) :负责存储发起人对象的内部状态。备忘录可以保持发起人的状态的一部分或全部信息。
  • 发起人(Originator) :创建一个备忘录对象,并且可以使用备忘录对象恢复自身的内部状态。发起人通常会在需要保存状态的时候创建备忘录对象,并在需要恢复状态的时候使用备忘录对象。
  • 管理员(Caretaker) :负责保存备忘录对象,但是不对备忘录对象进行操作或检查。管理员只能将备忘录传递给其他对象。

下面是一个完整的备忘录模式Demo,模拟文本编辑器的撤销功能。

备忘录,用来保存编辑器的状态。

// 备忘录类 - 保存编辑器的状态
class EditorMemento {
    private final String content;
​
    public EditorMemento(String content) {
        this.content = content;
    }
​
    public String getContent() {
        return content;
    }
}

发起人类,模拟文本编辑器。

// 发起人类 - 文本编辑器
class Editor {
    private String content = "";
​
    public void type(String words) {
        content = content + " " + words;
    }
​
    public String getContent() {
        return content;
    }
​
    // 保存当前状态到备忘录
    public EditorMemento save() {
        return new EditorMemento(content);
    }
​
    // 从备忘录恢复状态
    public void restore(EditorMemento memento) {
        content = memento.getContent();
    }
}

管理者类,保存备忘录。

// 管理者类 - 保存备忘录历史
class History {
    private List<EditorMemento> mementos = new ArrayList<>();
​
    public void push(EditorMemento memento) {
        mementos.add(memento);
    }
​
    public EditorMemento pop() {
        if (mementos.isEmpty()) {
            return null;
        }
        EditorMemento lastMemento = mementos.get(mementos.size() - 1);
        mementos.remove(lastMemento);
        return lastMemento;
    }
}

客户端,执行代码,输出测试结果。

// 客户端代码
public class MementoPatternDemo {
    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History();
​
        // 编辑内容并保存状态
        editor.type("This is the first sentence.");
        history.push(editor.save());
​
        editor.type("This is second.");
        history.push(editor.save());
​
        editor.type("This is third.");
​
        System.out.println("Current Content: " + editor.getContent());
​
        // 撤销一次
        editor.restore(history.pop());
        System.out.println("After first undo: " + editor.getContent());
​
        // 再次撤销
        editor.restore(history.pop());
        System.out.println("After second undo: " + editor.getContent());
    }
}

备忘录模式在需要重做/撤销功能的应用程序中非常有用,如文本编辑器、游戏等场景。实际上,我们使用到的大多数软件都用到了备忘录模式。

总结

备忘录模式是为了保存对象的内部状态,并在将来恢复到原先保存的状态。