欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Java 设计模式之备忘录模式

Java 设计模式之备忘录模式

2025/2/21 3:15:25 来源:https://blog.csdn.net/qq_14876133/article/details/145617696  浏览:    关键词:Java 设计模式之备忘录模式

文章目录

  • Java 设计模式之备忘录模式
    • 概述
    • UML
    • 代码实现

Java 设计模式之备忘录模式

概述

  • 备忘录(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。方便对该对象恢复到原先保存的状态。

UML

在这里插入图片描述

  • Originnator:发起者类,指需要被保存状态的对象,负责创建备忘录并恢复状态。
  • Memento:备忘录类,负责存储发起者的内部状态。
  • Caretaker:管理者类,负责保存和管理备忘录,不直接操作备忘录的内容。

代码实现

定义发起者类:

public class TextEditor {private String content;public String getContent() {return content;}public void setContent(String content) {this.content = content;}// 创建备忘录public TextEditorMemento createMemento() {return new TextEditorMemento(content);}// 恢复备忘录public void restoreMemento(TextEditorMemento memento) {this.content = memento.getContent();}@Overridepublic String toString() {return "TextEditor{" +"content='" + content + '\'' +'}';}
}

定义备忘录类:

public class TextEditorMemento {private final String content;public TextEditorMemento(String content) {this.content = content;}public String getContent() {return content;}
}

定义管理类:

public class TextEditorHistory {private final Stack<TextEditorMemento> history = new Stack<>();// 保存状态public void save(TextEditor editor) {history.push(editor.createMemento());}// 撤销操作public void undo(TextEditor editor) {if (!history.isEmpty()) {editor.restoreMemento(history.pop());} else {System.out.println("没有历史数据,不能撤销");}}
}

使用:

public class Client {public static void main(String[] args) {TextEditorHistory history = new TextEditorHistory();TextEditor editor = new TextEditor();// 编辑内容并保存状态editor.setContent("one");history.save(editor);System.out.println(editor);// 编辑内容并保存状态editor.setContent("two");history.save(editor);System.out.println(editor);// 只编辑内容editor.setContent("three");// 第1次撤销操作history.undo(editor);System.out.println("第1次撤销操作后:" + editor);// 第2次撤销操作history.undo(editor);System.out.println("第2次撤销操作后:" + editor);// 第3次撤销操作history.undo(editor);System.out.println("第3次撤销操作后:" + editor);}
}

输出:

TextEditor{content='one'}
TextEditor{content='two'}
第1次撤销操作后:TextEditor{content='two'}
第2次撤销操作后:TextEditor{content='one'}
没有历史数据,不能撤销
第3次撤销操作后:TextEditor{content='one'}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词