备忘录模式(Memento Pattern)是一种行为型设计模式,它允许在不暴露对象内部状态的情况下捕获和恢复对象的内部状态。该模式通过在对象之外保存和恢复对象的状态,使得对象可以在需要时回滚到之前的状态。
在备忘录模式中,有三个核心角色:
- 发起人(Originator):它是需要保存状态的对象。它可以创建一个备忘录对象,用于保存当前状态,并可以使用备忘录对象恢复其状态。
- 备忘录(Memento):它是保存发起人对象状态的对象。备忘录对象提供一个接口,允许发起人对象访问其内部状态(或者在某些情况下,允许其他对象访问)。
- 管理者(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
是管理者角色,它保存了多个备忘录对象,并提供了保存和恢复备忘录的方法。通过使用备忘录模式,我们可以在文本编辑器中保存多个状态,并在需要时恢复到之前的状态。