前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >设计模式-备忘录模式(三)

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

原创
作者头像
堕落飞鸟
发布2023-05-04 15:52:50
1560
发布2023-05-04 15:52:50
举报
文章被收录于专栏:飞鸟的专栏

定义负责人类

代码语言: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方法恢复到之前的状态,并输出当前状态。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 定义负责人类
  • 测试备忘录模式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档