Java学设计模式之备忘录模式

一、备忘录模式概念

1.1 什么是备忘录模式

备忘录模式是一种行为型设计模式,它允许在不破坏封装性的前提下捕获和恢复对象的内部状态。这种模式通常用于需要实现撤销操作或者历史记录功能的场景。

结构

备忘录模式通常包含以下几个要素:

  1. Originator(发起人): 定义了一个方法用于创建备忘录对象,并且可以通过备忘录对象恢复自身的状态。

  2. Memento(备忘录): 存储了发起人对象的内部状态。备忘录对象可以被发起人对象使用来恢复其内部状态。

  3. Caretaker(负责人): 负责保存备忘录对象,并且不能对备忘录对象的内容进行操作。负责人通常只负责存储备忘录对象,以便日后对发起人对象进行状态恢复。

二、备忘录模式代码

2.1 备忘录

public class EditorMemento {
    private final String content;

    public EditorMemento(String content) {
        this.content = content;
    }

    String getContent() {
        return content;
    }
}

2.2 发起人

public class TextEditor {
    private String content;

    void write(String content) {
        this.content = content;
    }

    EditorMemento save() {
        return new EditorMemento(content);
    }

    void restore(EditorMemento memento) {
        content = memento.getContent();
    }

    String getContent() {
        return content;
    }

}

2.3 负责人

public class History {
    private final List<EditorMemento> mementos = new ArrayList<>();

    void save(EditorMemento memento) {
        mementos.add(memento);
    }

    EditorMemento getLastSaved() {
        if (!mementos.isEmpty()) {
            return mementos.remove(mementos.size() - 1);
        }
        return null;
    }
}

2.4 测试类

public class MementoPatternTest {
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        History history = new History();

        editor.write("Hello,world!");
        history.save(editor.save());

        editor.write("This is a new content.");
        history.save(editor.save());

        System.out.println("Current content:" + editor.getContent());

        EditorMemento savedMemento = history.getLastSaved();
        if (savedMemento != null) {
            editor.restore(savedMemento);
        }
        System.out.println("Content after restoring:" + editor.getContent());
        // 输出:
        // Current content:This is a new content.
        // Content after restoring:This is a new content.
    }
}

三、总结

备忘录模式的优点包括:

  • 可以在不破坏对象封装性的前提下保存和恢复对象的内部状态。
  • 可以实现撤销和恢复操作,提供了良好的用户体验。

缺点包括:

  • 如果备忘录对象很大或者需要频繁保存,可能会消耗大量的内存和处理时间。
  • 发起人对象需要负责管理备忘录对象,可能会增加其复杂性。备忘录模式是一种行为型设计模式,允许在不暴露对象实现细节的情况下保存和恢复其内部状态。它通常在需要实现撤销、恢复或历史记录功能的场景中使用。
posted @ 2024-05-10 14:18  Kllin  阅读(6)  评论(0编辑  收藏  举报