package memento; /** * Originator — the text editor whose state we're saving and restoring. * Creates mementos and restores from them; no history management here. */ public class Editor { private String content = ""; private int cursorPosition = 0; private String selectedText = ""; public void type(String text) { content = content.substring(0, cursorPosition) + text + content.substring(cursorPosition); cursorPosition += text.length(); } public void selectText(int start, int end) { this.selectedText = content.substring(start, end); System.out.println(" Selected: \"" + selectedText + "\""); } public void deleteSelection() { content = content.replace(selectedText, ""); selectedText = ""; } /** Create a snapshot of current state */ public EditorMemento save() { return new EditorMemento(content, cursorPosition, selectedText); } /** Restore state from a snapshot */ public void restore(EditorMemento memento) { this.content = memento.getContent(); this.cursorPosition = memento.getCursorPosition(); this.selectedText = memento.getSelectedText(); } @Override public String toString() { return "Editor[\"" + content + "\", cursor=" + cursorPosition + "]"; } }