public class TextEditorHistory {
private Stack<TextEditorMemento> mementos = new Stack<>();
public void save(TextEditor editor) {
mementos.push(editor.createMemento());
}
public void undo(TextEditor editor) {
if (!mementos.isEmpty()) {
TextEditorMemento memento = mementos.pop();
editor.restoreMemento(memento);
}
}
}
负责人类TextEditorHistory包含了保存备忘录和恢复状态的方法。它通过一个Stack来保存备忘录,当需要恢复状态时,从栈中弹出最后一个备忘录,并将其传递给发起人类TextEditor。
public class Test {
public static void main(String[] args) {
TextEditor editor = new TextEditor("Hello, world!");
TextEditorHistory history = new TextEditorHistory();
// Save the initial state
history.save(editor);
// Modify the text and position
editor.setText("Goodbye, world!");
editor.setCursorPosition(7);
// Save the new state
history.save(editor);
// Undo the last change
history.undo(editor);
// Check the current state
System.out.println(editor.getText()); // Output: Hello, world!
System.out.println(editor.getCursorPosition()); // Output: 0
}
}
在上面的示例代码中,我们首先创建一个TextEditor对象和一个TextEditorHistory对象。然后,我们修改TextEditor的文本和光标位置,并保存了两个备忘录。最后,我们使用undo方法恢复到之前的状态,并输出当前状态。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。