
memento 模式解决了在不违反对象封装的情况下捕获和恢复对象内部状态的需求。这在您想要实现撤消/重做功能、允许对象恢复到之前状态的场景中非常有用。
memento 模式涉及三个主要组成部分:
发起者创建一个包含其当前状态快照的备忘录。然后,管理员可以存储该备忘录,并在需要时用于恢复发起者的状态。
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<Editor.Memento> 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 设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号