设计模式-备忘录模式(三)

2023-05-04 15:52:50 浏览数 (5)

定义负责人类

代码语言:javascript复制
public class TextEditorHistory {
    private Stack<TextEditorMemento> mementos = new Stack<>();

    public void save(TextEditor editor) {
        mementos.push(editor.createMemento());
    }

    public void undo(TextEditor editor) {
        if (!mementos.isEmpty()) {
            TextEditorMemento memento = mementos.pop();
            editor.restoreMemento(memento);
        }
    }
}

负责人类TextEditorHistory包含了保存备忘录和恢复状态的方法。它通过一个Stack来保存备忘录,当需要恢复状态时,从栈中弹出最后一个备忘录,并将其传递给发起人类TextEditor。

测试备忘录模式

代码语言:javascript复制
public class Test {
    public static void main(String[] args) {
        TextEditor editor = new TextEditor("Hello, world!");
        TextEditorHistory history = new TextEditorHistory();

        // Save the initial state
        history.save(editor);

        // Modify the text and position
        editor.setText("Goodbye, world!");
        editor.setCursorPosition(7);

        // Save the new state
        history.save(editor);

        // Undo the last change
        history.undo(editor);

        // Check the current state
        System.out.println(editor.getText());           // Output: Hello, world!
        System.out.println(editor.getCursorPosition()); // Output: 0
    }
}

在上面的示例代码中,我们首先创建一个TextEditor对象和一个TextEditorHistory对象。然后,我们修改TextEditor的文本和光标位置,并保存了两个备忘录。最后,我们使用undo方法恢复到之前的状态,并输出当前状态。

0 人点赞