← Back to list

Memento Pattern — CTRL+Z for Your Software — DAY 21

“Everyone wishes life had an Undo button. Well, in software, we actually can build one.”

Sugam Arora · 2025-10-16 05:31 · 54 claps · 4.4 min read
#low-level-design #sugam #memento-pattern #software-engineering #design-patterns
Open on Medium ↗
Wiki topics: CUL · Culture & Media 😂 · Humor & Satire

Memento Pattern — CTRL+Z for Your Software — DAY 21

“Everyone wishes life had an Undo button. Well, in software, we actually can build one.”

Free !! -> https://medium.com/@sugam.arora23/memento-pattern-ctrl-z-for-your-software-day-21-63d1765d7ccb?sk=9adc04eaf1d9e9ee57c1a4cf2bf3ca18

The Core Idea

Imagine you’re writing an important essay. After three hours, you accidentally delete a paragraph that was pure gold. You wish you could just press CTRL+Z and get it back. That’s exactly what the Memento Pattern gives your software — the ability to capture an object’s internal state, store it safely, and restore it later without exposing its internal details.

At its heart, the Memento Pattern is about time travel for objects. It allows your program to “bookmark” an object’s state at a particular moment, then revert to that state whenever needed.

Why Do We Need It?

Think of apps you use daily:

  • Word processors like Google Docs or MS Word — Undo, Redo
  • Photo editors — Restore to original
  • Games — Save checkpoints and load them later
  • Coding IDEs — Version history or local history

All these features rely on the same underlying principle: saving and restoring object state safely.

That’s the Memento pattern working silently behind the scenes — the guardian angel of your software’s memory.

The Three Key Components

The Memento pattern involves three main players — like a secret operation team where each has a defined role:

1. Originator

The main object whose state you want to save. It creates a Memento and can restore its state from one.

2. Memento

The actual “snapshot” — an object that stores the state. It’s private — no one can directly tamper with it.

3. Caretaker

The one who manages these snapshots (like a game’s save manager). It asks the Originator to create/restore states but never peeks inside.

Real-Life Analogy: “CTRL+Z in Real Life”

Think of writing a long WhatsApp message. You keep editing and rephrasing. Then, you suddenly feel your earlier version was better. If you had a “Save” button at each step, you could jump back to any message version you liked.

That’s what the Caretaker (your phone) and the Memento (your saved messages) do behind the scenes — allowing you to undo or redo effortlessly.

Code Example in Java

Let’s take an example where we’re editing a text document and want to save and revert states.

// The Memento - stores the state of the editor
class EditorMemento {
    private final String content;
public EditorMemento(String content) {
        this.content = content;
    }
    public String getContent() {
        return content;
    }
}
// The Originator - creates and restores mementos
class Editor {
    private String content = "";
    public void type(String words) {
        content += words;
    }
    public String getContent() {
        return content;
    }
    public EditorMemento save() {
        return new EditorMemento(content);
    }
    public void restore(EditorMemento memento) {
        content = memento.getContent();
    }
}
// The Caretaker - manages save points
class History {
    private final Stack<EditorMemento> history = new Stack<>();
    public void save(Editor editor) {
        history.push(editor.save());
    }
    public void undo(Editor editor) {
        if (!history.isEmpty()) {
            editor.restore(history.pop());
        }
    }
}
public class MementoDemo {
    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History();
        editor.type("Hello ");
        editor.type("World!");
        history.save(editor);
        editor.type(" This is Sugam's article on Memento Pattern.");
        System.out.println("Current: " + editor.getContent());
        history.undo(editor);
        System.out.println("After Undo: " + editor.getContent());
    }
}

Output:

Current: Hello World! This is Sugam's article on Memento Pattern.
After Undo: Hello World!

Simple, powerful, elegant.

How It Works Step-by-Step

  1. Editor (Originator) keeps writing text.
  2. History (Caretaker) saves checkpoints using editor.save().
  3. When you undo, history.undo() asks the editor to restore from its last Memento.

Just like hitting CTRL+Z — back to your last known good version.

When to Use the Memento Pattern

When you need to implement undo/redo functionality When you want to save checkpoints in apps/games When you want to hide object internals from external modification When maintaining object history is important (e.g., in editors or financial systems)

Pros and Cons

Advantages:

  • Preserves encapsulation (state details are hidden)
  • Enables rollback or undo
  • Easy to integrate with caretakers

Disadvantages:

  • Memory-heavy if many states are stored
  • Complexity grows with nested objects

Visual Diagram

+----------------+      +----------------+      +----------------+
|   Caretaker    | ---> |   Originator   | ---> |    Memento     |
| (manages saves)|      | (creates/loads)|      | (stores state) |
+----------------+      +----------------+      +----------------+

Conclusion

The Memento Pattern is one of those quiet heroes in system design. It doesn’t change how things look, but it changes how confidently you can move forward — because you know you can always go back.

From games to IDEs to writing apps — every “Undo” we take for granted exists because of this simple yet profound idea:

“Save the past to secure the future.”

So next time you hit CTRL+Z, remember — you’re invoking one of the most elegant patterns in software design.

Thank you for taking the time to read my blog. Your feedback is immensely valuable to me. Please feel free to share your thoughts and suggestions.


메타데이터
post_id
63d1765d7ccb
slug
memento-pattern-ctrl-z-for-your-software-day-21-63d1765d7ccb
url
https://medium.com/@sugamsays/memento-pattern-ctrl-z-for-your-software-day-21-63d1765d7ccb
canonical_url
https://medium.com/@sugamsays/memento-pattern-ctrl-z-for-your-software-day-21-63d1765d7ccb
author_url
https://medium.com/@sugamsays
status
ok
fetched_at
2026-07-25 22:50:20