当前位置: 首页 > news >正文

Java设计模式之备忘录模式

备忘录模式(Memento Pattern)是一种行为型设计模式,它允许在不暴露对象内部状态的情况下捕获和恢复对象的内部状态。该模式通过在对象之外保存和恢复对象的状态,使得对象可以在需要时回滚到之前的状态。

在备忘录模式中,有三个核心角色:

  1. 发起人(Originator):它是需要保存状态的对象。它可以创建一个备忘录对象,用于保存当前状态,并可以使用备忘录对象恢复其状态。
  2. 备忘录(Memento):它是保存发起人对象状态的对象。备忘录对象提供一个接口,允许发起人对象访问其内部状态(或者在某些情况下,允许其他对象访问)。
  3. 管理者(Caretaker):它负责保存和恢复备忘录对象。管理者对象可以存储多个备忘录对象,并在需要时将其提供给发起人对象。

下面是一个示例,展示了如何使用备忘录模式来保存和恢复发起人对象的状态。假设我们有一个文本编辑器,用户可以输入文本并进行撤销操作。

// 发起人(Originator)
class TextEditor {private String text;public void setText(String text) {this.text = text;}public String getText() {return text;}public TextEditorMemento save() {return new TextEditorMemento(text);}public void restore(TextEditorMemento memento) {this.text = memento.getText();}
}// 备忘录(Memento)
class TextEditorMemento {private String text;public TextEditorMemento(String text) {this.text = text;}public String getText() {return text;}
}// 管理者(Caretaker)
class TextEditorHistory {private Stack<TextEditorMemento> history = new Stack<>();public void push(TextEditorMemento memento) {history.push(memento);}public TextEditorMemento pop() {return history.pop();}
}// 示例使用
public class Main {public static void main(String[] args) {TextEditor textEditor = new TextEditor();TextEditorHistory history = new TextEditorHistory();// 编辑文本textEditor.setText("Hello, World!");// 保存状态history.push(textEditor.save());// 修改文本textEditor.setText("Hello, Java!");// 保存状态history.push(textEditor.save());// 恢复到之前的状态textEditor.restore(history.pop());System.out.println(textEditor.getText());  // 输出: Hello, Java!textEditor.restore(history.pop());System.out.println(textEditor.getText());  // 输出: Hello, World!}
}

在上面的示例中,TextEditor 是发起人角色,它保存了文本编辑器的状态,并提供了保存和恢复状态的方法。TextEditorMemento 是备忘录角色,它保存了发起人对象的状态。TextEditorHistory 是管理者角色,它保存了多个备忘录对象,并提供了保存和恢复备忘录的方法。通过使用备忘录模式,我们可以在文本编辑器中保存多个状态,并在需要时恢复到之前的状态。

推荐一个ChatGPT使用渠道:点击直达
http://www.lryc.cn/news/197938.html

相关文章:

  • 深度学习 | Pytorch深度学习实践
  • Elasticsearch7.9.3保姆级安装教程
  • 深入使用探讨 PuppeteerSharp 抓取 LinkedIn 页面的步骤
  • 联合体(共用体)
  • 从零开始:GitFlow详细教程,轻松掌握分支策略
  • 深度学习硬件介绍
  • 利用向导创建MFC
  • MySQL 8.0 OCP认证精讲视频、环境和题库之五 事务、缓存
  • ACL配置
  • 微信小程序修改van-popup的背景颜色
  • SpringCloud-Nacos
  • 动态规划12(Leetcode221最大正方形)
  • 【Git】bad signature 0x00000000 index file corrupt. fatal: index file corrupt
  • GO 语言的函数??
  • 机器学习基础之《回归与聚类算法(3)—线性回归优化:岭回归》
  • DirectX3D 正交投影学习记录
  • 数据挖掘十大算法--Apriori算法
  • [蓝桥杯 2022 省 B] 统计子矩阵
  • 解决在部署springboot项目的docker中执行备份与之相连接的mysql容器命令
  • 正文Delphi XE Android下让TMemo不自动弹出键盘
  • [1Panel]开源,现代化,新一代的 Linux 服务器运维管理面板
  • PG集合查询
  • 目标检测应用场景和发展趋势
  • Confluence 自定义博文列表
  • chrome历史版本下载
  • Messari发布Moonbeam简报,每日交易量稳步增长,首次公布利润数据
  • 数据库 锁、索引、在实际开发中怎么设置和优化
  • 超详细彻底卸载Anaconda详细教程
  • Python--随机出拳(random)--if判断--综合案例练习:石头剪刀布
  • 微信小程序里配置less