Problem Overview
The TextEditor class keeps its text in one content field. write() replaces that text.
The class has no way to:
- Save previous states.
- Restore older versions of the content.
So undo/redo is impossible.
Design Issues
-
No State Preservation
- Each call to
write()replacescontent, so the old text is lost. - There is no way to go back to a previous state.
- Each call to
-
Encapsulation Violation Risk
- If we add undo/redo inside
TextEditor, other code would need to see its internal state. - This would break encapsulation (the data should stay private). It would also break the Single Responsibility Principle (SRP), which says a class should do one job. The editor should not manage history.
- If we add undo/redo inside
-
Tight Coupling
- If
TextEditoralso managed history, editing and history code would mix in one class. It would be harder to maintain or extend.
- If
Core Problem
How can we add undo/redo, or restore an old state, without exposing the internal state of
TextEditorand without violating SRP?
The Memento Pattern solves this by introducing:
- A separate
Mementoclass (EditorMementoin After) to hold snapshots of the editor’s state. - A
Caretaker(e.g., aHistoryclass) to keep the mementos.
Each class has one job. The editor's data stays private.