Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
43
03-behavioral/memento/Editor.java
Normal file
43
03-behavioral/memento/Editor.java
Normal file
@@ -0,0 +1,43 @@
|
||||
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 + "]";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user