备忘录模式(Memento)是一种行为型设计模式,它允许在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后可以将该对象恢复到原先保存的状态。
在备忘录模式中,有三个主要的角色:
Originator(发起人):负责创建一个备忘录,并记录自己的当前状态。
Memento(备忘录):用于存储Originator的状态。
Caretaker(管理者):负责保存备忘录,并在需要时将其恢复到原始状态。
下面是一个简单的备忘录模式的实现:
// Originator
public class TextEditor {
private String text;
public TextEditor(String text) {
this.text = text;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public Memento save() {
return new Memento(text);
}
public void restore(Memento memento) {
text = memento.getText();
}
}
// Memento
public class Memento {
private String text;
public Memento(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
// Caretaker
public class TextEditorHistory {
private Stack<Memento> history = new Stack<>();
public void save(TextEditor editor) {
history.push(editor.save());
}
public void undo(TextEditor editor) {
if (!history.isEmpty()) {
editor.restore(history.pop());
}
}
}
// Usage
public class Main {
public static void main(String[] args) {
TextEditor editor = new TextEditor("Hello, world!");
TextEditorHistory history = new TextEditorHistory();
history.save(editor);
editor.setText("Goodbye, world!");
history.save(editor);
System.out.println(editor.getText()); // "Goodbye, world!"
history.undo(editor);
System.out.println(editor.getText()); // "Hello, world!"
}
}在上面的例子中,TextEditor是发起人,它保存了一个字符串的状态。Memento是备忘录,它保存了TextEditor的状态。
TextEditorHistory是管理者,它保存了TextEditor的历史状态,并可以将其恢复到以前的状态。
在Main类中,我们创建了一个TextEditor和一个TextEditorHistory,并使用它们来保存和恢复TextEditor的状态。