Skip to content

Memento Pattern — Short Notes

Save and restore an object's state

Builds on Encapsulation

Stage 3advanced1 min read

Definition

Think of the undo button in a text editor. When you type new text, the old text is gone unless something saved it. The Memento Pattern is a behavioral design pattern that lets an object save a copy of its state and restore it later. The object does not show its inner data to anyone.

It is used to build undo/redo. It keeps encapsulation, which means the object's data stays private.


Key Components

  1. Originator: The object whose state needs to be saved (e.g., TextEditor). It creates and reads the snapshots.
  2. Memento: A snapshot (a saved copy) of the Originator's state (e.g., EditorMemento).
  3. Caretaker: Keeps the mementos, for example in a stack. It does not open or change them.

Benefits

  • Makes undo/redo simple to add.
  • Keeps encapsulation: the internal state stays private.
  • Makes state easier to manage in editors, games, or transactions.

Real-world Example

  • Text editors (Undo/Redo).
  • Version control systems.
  • Graphic design tools with history tracking.

In this topic

Done with this topic?

How well do you know it?

PreviousSequential Request Processing