备忘录模式(Memento Pattern)
备忘录模式是一种设计模式,它允许在不破坏封装性的情况下保存和恢复对象的状态。这种模式通常用于需要提供撤销或恢复操作的应用程序中。
使用场景
-
需要提供撤销操作的应用程序,例如文本编辑器等。在这种情况下,备忘录模式可以用于保存对象的历史状态,并在需要时恢复对象的状态。
-
需要保存对象状态以进行后续恢复的应用程序。例如,游戏保存和恢复状态。
-
需要在不破坏对象封装性的情况下保存和恢复对象状态的应用程序。
-
需要跟踪和记录对象状态变化的应用程序。例如,监控和记录系统状态变化。
代码实现
假设我们有一个文本编辑器类,需要提供撤销和恢复操作:
public class TextEditor {
private String text;
private Stack<TextEditorMemento> undoStack;
private Stack<TextEditorMemento> redoStack;
public TextEditor(String text) {
this.text = text;
this.undoStack = new Stack<>();
this.redoStack = new Stack<>();
}
public void setText(String text) {
undoStack.push(new TextEditorMemento(this.text));
this.text = text;
redoStack.clear();
}
public String getText() {
return text;
}
public void undo() {
if (!undoStack.isEmpty()) {
redoStack.push(new TextEditorMemento(this.text));
this.text = undoStack.pop().getText();
}
}
public void redo() {
if (!redoStack.isEmpty()) {
undoStack.push(new TextEditorMemento(this.text));
this.text = redoStack.pop().getText();
}
}
private static class TextEditorMemento {
private final String text;
public TextEditorMemento(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
}
public class Main {
public static void main(String[] args) {
TextEditor editor = new TextEditor("Hello World");
System.out.println(editor.getText()); // output: Hello World
editor.setText("Goodbye World");
System.out.println(editor.getText()); // output: Goodbye World
editor.undo();
System.out.println(editor.getText()); // output: Hello World
editor.redo();
System.out.println(editor.getText()); // output: Goodbye World
}
}
TextEditor是文本编辑器类,它有一个文本属性text,并且有两个栈undoStack和redoStack,用于保存备忘录。setText()方法用于设置文本,并将旧的文本备份到undoStack中。undo()方法用于撤销操作,从undoStack中取出上一个备忘录,并将当前文本备份到redoStack中。redo()方法用于恢复操作,从redoStack中取出上一个备忘录,并将当前文本备份到undoStack中
使用小结
通过使用备忘录模式,我们可以轻松地提供撤销和恢复操作,同时保持其封装性和简洁性。如果需要实现多次撤销和恢复操作,我们只需要保存多个备忘录即可。
评论( 0 )