备忘录模式(Memento Pattern)是一种行为型设计模式,它允许在不暴露对象内部状态的情况下捕获和恢复对象的内部状态。该模式通过在对象之外保存和恢复对象的状态,使得对象可以在需要时回滚到之前的状态。
在备忘录模式中,有三个核心角色:
下面是一个示例,展示了如何使用备忘录模式来保存和恢复发起人对象的状态。假设我们有一个文本编辑器,用户可以输入文本并进行撤销操作。
// 发起人(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
是管理者角色,它保存了多个备忘录对象,并提供了保存和恢复备忘录的方法。通过使用备忘录模式,我们可以在文本编辑器中保存多个状态,并在需要时恢复到之前的状态。