public class TextEditor {
private String documentText;
public TextEditor(String initialText) {
this.documentText = initialText;
}
public void insertText(String text, int position) {
StringBuilder newDocumentText = new StringBuilder(documentText);
newDocumentText.insert(position, text);
documentText = newDocumentText.toString();
System.out.println("Inserted text: " + text);
}
public void deleteText(String text, int startPosition, int endPosition) {
StringBuilder newDocumentText = new StringBuilder(documentText);
newDocumentText.delete(startPosition, endPosition);
documentText = newDocumentText.toString();
System.out.println("Deleted text: " + text);
}
public String getDocumentText() {
return documentText;
}
public Memento createMemento() {
return new Memento(documentText);
}
public void restoreMemento(Memento memento) {
this.documentText = memento.getDocumentText();
}
public static class Memento {
private String documentText;
public Memento(String documentText) {
this.documentText = documentText;
}
public String getDocumentText() {
return documentText;
}
}
}
public class Client {
public static void main(String[] args) {
TextEditor editor = new TextEditor("This is the initial text.");
Memento memento1 = editor.createMemento(); // Save state after initial text
editor.insertText("Hello, ", 5); // Insert text
Memento memento2 = editor.createMemento(); // Save state after inserting text
editor.deleteText("world", 12, 16); // Delete text
System.out.println("Current document text: " + editor.getDocumentText());
// Restore state to before inserting text
editor.restoreMemento(memento1);
System.out.println("Restored document text (before inserting text): " + editor.getDocumentText());
// Restore state to before deleting text
editor.restoreMemento(memento2);
System.out.println("Restored document text (before deleting text): " + editor.getDocumentText());
}
}