欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 23种设计模式中的备忘录模式

23种设计模式中的备忘录模式

2025/4/2 8:45:37 来源:https://blog.csdn.net/cijiancao/article/details/146691438  浏览:    关键词:23种设计模式中的备忘录模式

在不破坏封装的前提下,捕获一个对象的内部状态,并允许在对象之外保存和恢复这些状态。

备忘录模式,主要用于捕获并保存一个对象的内部状态,以便将来可以恢复到该状态。

备忘录的模式主要由三个角色来实现:备忘录、发起人和管理员。

  • 备忘录(Memento):负责存储发起人对象的内部状态。备忘录可以保持发起人的状态的一部分或全部信息。
  • 发起人(Originator):创建一个备忘录对象,并且可以使用备忘录对象恢复自身的内部状态。发起人通常会在需要保存状态的时候创建备忘录对象,并在需要恢复状态的时候使用备忘录对象。
  • 管理员(Caretaker):负责保存备忘录对象,但是不对备忘录对象进行操作或检查。管理员只能将备忘录传递给其他对象。

下面是一个完整的备忘录模式Demo,模拟文本编辑器的撤销功能。

备忘录,用来保存编辑器的状态。

// 备忘录类 - 保存编辑器的状态
class EditorMemento {private final String content;public EditorMemento(String content) {this.content = content;}public String getContent() {return content;}
}

发起人类,模拟文本编辑器。

// 发起人类 - 文本编辑器
class Editor {private String content = "";public void type(String words) {content = content + " " + words;}public String getContent() {return content;}// 保存当前状态到备忘录public EditorMemento save() {return new EditorMemento(content);}// 从备忘录恢复状态public void restore(EditorMemento memento) {content = memento.getContent();}
}

管理者类,保存备忘录。

// 管理者类 - 保存备忘录历史
class History {private List<EditorMemento> mementos = new ArrayList<>();public void push(EditorMemento memento) {mementos.add(memento);}public EditorMemento pop() {if (mementos.isEmpty()) {return null;}EditorMemento lastMemento = mementos.get(mementos.size() - 1);mementos.remove(lastMemento);return lastMemento;}
}

客户端,执行代码,输出测试结果。

// 客户端代码
public class MementoPatternDemo {public static void main(String[] args) {Editor editor = new Editor();History history = new History();// 编辑内容并保存状态editor.type("This is the first sentence.");history.push(editor.save());editor.type("This is second.");history.push(editor.save());editor.type("This is third.");System.out.println("Current Content: " + editor.getContent());// 撤销一次editor.restore(history.pop());System.out.println("After first undo: " + editor.getContent());// 再次撤销editor.restore(history.pop());System.out.println("After second undo: " + editor.getContent());}
}

备忘录模式在需要重做/撤销功能的应用程序中非常有用,如文本编辑器、游戏等场景。实际上,我们使用到的大多数软件都用到了备忘录模式。

总结

备忘录模式是为了保存对象的内部状态,并在将来恢复到原先保存的状态。

版权声明:

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

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

热搜词