Skip to main content

What does the Memento pattern do?

The Memento pattern is designed to save and restore an object's state without breaking its encapsulation.


1. The Core Idea

Memento lets an object "photograph" its internal state and later "roll back" to it, without exposing implementation details.

In other words: Memento is "Ctrl+Z" for objects.


2. Roles Involved

  • Originator - the object whose state needs to be saved. It creates a snapshot and can restore itself from it.
  • Memento - the object that stores the saved state. Its internals are hidden from the outside world.
  • Caretaker - an external object that stores snapshots, but has no access to their contents (for example, an action history).

3. Example (Java)

java
// Memento class Memento { private final String state; public Memento(String state) { this.state = state; } public String getState() { return state; } } // Originator class Editor { private String text; public void setText(String text) { this.text = text; } public String getText() { return text; } public Memento save() { return new Memento(text); } public void restore(Memento memento) { text = memento.getState(); } } // Caretaker class History { private Stack<Memento> history = new Stack<>(); public void push(Memento m) { history.push(m); } public Memento pop() { return history.pop(); } }

Usage:

java
Editor editor = new Editor(); History history = new History(); editor.setText("Version 1"); history.push(editor.save()); editor.setText("Version 2"); editor.restore(history.pop()); // rollback to "Version 1"

4. Advantages

  • Allows you to implement undo/redo without breaking encapsulation.
  • Separates responsibility: the object holds the logic, the caretaker holds the history.
  • Safely stores internal states (other objects don't see the details).

5. Disadvantages

  • Can consume a lot of memory if states are large or saved frequently.
  • Hard to implement if the state is spread across many objects.

Conclusion

The Memento pattern is needed to:

  • store "snapshots" of an object's state,
  • roll back to previous versions,
  • while not exposing internal data.

Summary:

Memento is a way to "freeze" an object in time and then return it there, without violating the encapsulation principle.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.