Design patterns

patterns18MementoPattern

Path
pkg8patterns/patterns18MementoPattern.java
Package
pkg8patterns
Study order
18
Run
Single-file source launch
Command
java pkg8patterns/patterns18MementoPattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns18MementoPattern.java
1package pkg8patterns;2 3/*4 * Memento (Behavioral)5 * --------------------6 * INTENT: capture and externalize an object's internal state (without violating7 *         encapsulation) so it can be restored later (undo).8 * UML: Originator + save(): Memento + restore(Memento) ; Caretaker stores mementos.9 * PROS: clean undo/redo; encapsulation preserved.10 * CONS: memory cost if state is large/frequent.11 * REAL-WORLD: editor undo, transactions/savepoints, game checkpoints.12 */13import java.util.*;14 15public class patterns18MementoPattern {16 17    // Memento: an immutable snapshot18    record Memento(String content) {}19 20    // Originator21    static class Editor {22        private StringBuilder content = new StringBuilder();23        void type(String text) { content.append(text); }24        String getContent() { return content.toString(); }25        Memento save() { return new Memento(content.toString()); }26        void restore(Memento m) { content = new StringBuilder(m.content()); }27    }28 29    // Caretaker30    static class History {31        private final Deque<Memento> stack = new ArrayDeque<>();32        void push(Memento m) { stack.push(m); }33        Memento pop() { return stack.pop(); }34        boolean isEmpty() { return stack.isEmpty(); }35    }36 37    public static void main(String[] args) {38        Editor editor = new Editor();39        History history = new History();40 41        editor.type("Hello");42        history.push(editor.save());          // checkpoint 143        editor.type(", World");44        history.push(editor.save());          // checkpoint 245        editor.type("!!! oops");46 47        System.out.println("current: " + editor.getContent());48        editor.restore(history.pop());        // undo to checkpoint 249        System.out.println("after undo: " + editor.getContent());50        editor.restore(history.pop());        // undo to checkpoint 151        System.out.println("after undo: " + editor.getContent());52    }53}