文章目录
- 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'}