登录
首页 >  文章 >  java教程

理解 Java 中的 Memento 设计模式

来源:dev.to

时间:2024-07-24 12:15:54 290浏览 收藏

目前golang学习网上已经有很多关于文章的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《理解 Java 中的 Memento 设计模式》,也希望能帮助到大家,如果阅读完后真的对你学习文章有帮助,欢迎动动手指,评论留言并分享~

理解 Java 中的 Memento 设计模式

问题

memento 模式解决了在不违反对象封装的情况下捕获和恢复对象内部状态的需求。这在您想要实现撤消/重做功能、允许对象恢复到之前状态的场景中非常有用。

解决方案

memento 模式涉及三个主要组成部分:

  1. originator: 需要保存和恢复内部状态的对象。
  2. memento: 存储发起者内部状态的对象。纪念品是一成不变的。
  3. caretaker: 负责请求发起者从备忘录中保存或恢复其状态。

发起者创建一个包含其当前状态快照的备忘录。然后,管理员可以存储该备忘录,并在需要时用于恢复发起者的状态。

优点和缺点

优点

  • 保留封装:允许保存和恢复对象的内部状态而不暴露其实现细节。
  • 简单的撤消/重做: 方便实现撤消/重做功能,使系统更加健壮和用户友好。
  • 状态历史记录: 允许维护对象先前状态的历史记录,从而实现不同状态之间的导航。

缺点

  • 内存消耗:存储多个备忘录会消耗大量内存,特别是当对象的状态很大时。
  • 额外的复杂性: 给代码带来了额外的复杂性,需要管理纪念品的创建和恢复。
  • 看护者责任: 看护者需要有效地管理纪念品,这会增加系统的责任和复杂性。

实际应用示例

memento 模式的一个实际示例是提供撤消/重做功能的文本编辑器。对文档的每次更改都可以保存为备忘录,允许用户根据需要恢复到文档之前的状态。

java 中的示例代码

代码中的备忘录模式:

// Originator
public class Editor {
    private String content;

    public void setContent(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public Memento save() {
        return new Memento(content);
    }

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

    // Memento
    public static class Memento {
        private final String content;

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

        private String getContent() {
            return content;
        }
    }
}

// Caretaker
public class History {
    private final Stack history = new Stack<>();

    public void save(Editor editor) {
        history.push(editor.save());
    }

    public void undo(Editor editor) {
        if (!history.isEmpty()) {
            editor.restore(history.pop());
        }
    }
}

// Client code
public class Client {
    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History();

        editor.setContent("Version 1");
        history.save(editor);
        System.out.println(editor.getContent());

        editor.setContent("Version 2");
        history.save(editor);
        System.out.println(editor.getContent());

        editor.setContent("Version 3");
        System.out.println(editor.getContent());

        history.undo(editor);
        System.out.println(editor.getContent());

        history.undo(editor);
        System.out.println(editor.getContent());
    }
}

终于介绍完啦!小伙伴们,这篇关于《理解 Java 中的 Memento 设计模式》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>