Design Patterns Simplified: Part 12 — Memento Pattern (a.k.a. “Your Object’s Time Machine”)



This content originally appeared on DEV Community and was authored by Prateek Prabhakar

The Memento Pattern belongs to the Behavioral category of design patterns.

Why? Because it focuses on how objects capture and restore their past states (like an Undo), all while keeping their internal details private.
It gives your application the power to,

  1. Save a snapshot of an object’s state
  2. Restore it to that state later
  3. Do this all without exposing the object’s internal structure

It is like giving your object a Time Machine, so it can rewind to a known good state when things go wrong.

Let’s take an example of the Shopping Cart Undo

Imagine you are shopping online,

  • You add a Phone to your cart.
  • Then a pair of Headphones.
  • Then a Charger.

Then suddenly, you accidentally delete the headphones from your cart. Oops! But no worries. You click ‘Undo’, and they are magically back.

That is the Memento Pattern in action.
Each time you make a change, your system quietly saves a snapshot of the cart.
When you click Undo, it just restores the last saved version.

What is the Momento Pattern?

It allows an object to capture and store its internal state so it can be restored later, all without exposing its internal details.

It involves 3 main parts,

  • Originator: The object whose state we want to save/restore (e.g. Shopping Cart)
  • Memento: A value object storing the Originator’s state
  • Caretaker: Manages the history of Mementos, e.g. to allow undo/redo

Wiki Document with Version History

Let’s say you are editing a wiki document. You write, you revise, you delete, and eventually hit Publish.

Oops! You just realized you deleted an important paragraph. What would you do?
Mostly, you would like to revert it to a previous published version.

Each time you publish, the system silently saves the document’s current state. Later, you can roll back to any of those versions.

That is exactly what the Memento Pattern helps you do in code.

What does the code look like?

Say we want to mimic the code for how the wiki might be built with following features,

  • You can publish new versions
  • View current content
  • Undo to a previous version
//Step 1: Define the Memento (saved version of the document)
Class WikiMemento
    Constructor(content)
        this.content = content

    Method GetContent()
        return content

//Step 2: Define the Originator (Wiki Document)
Class WikiDocument
    Property content

    Method Write(text)
        content = text

    Method Show()
        Print("Current Content: " + content)

    Method Save()
        return new WikiMemento(content)

    Method Restore(memento)
        content = memento.GetContent()

//Step 3: Define the Caretaker (History Manager)
Class VersionHistory
    Property history = []

    Method SaveVersion(memento)
        history.Push(memento)

    Method Undo()
        If history is not empty:
            return history.Pop()
        Else:
            return null

//caller logic
// Initialize components
doc = new WikiDocument()
history = new VersionHistory()

// First version
doc.Write("Initial Draft of Wiki Page")
history.SaveVersion(doc.Save())

// Update version
doc.Write("Added introduction and summary")
history.SaveVersion(doc.Save())

// Another update
doc.Write("Removed summary by mistake...")
doc.Show()

// Undo last change
prev = history.Undo()
doc.Restore(prev)
doc.Show()

Just like hitting Undo in your document editor, your application brings back the last published version.

NOTE: In real world apps, you might want to undo to any specific version, not just the last one. This is also supported by the Memento Pattern but can add complexity. To keep things simple, here the example focuses on undoing the most recent change.

What Did We Achieve?

  • Internal state saved without exposing implementation
  • Clean separation between state management and history tracking
  • Reversible actions (Undo/Redo behavior)
  • It is scalable. You can add version limits, redo stacks, timestamps and more.

When Should You Use It?

  • When you want to implement undo/redo
  • When you need state checkpoints (e.g., autosave, game saves)
  • When you need to log or rollback user actions

Use Cases?

  • Document editors (Google Docs, Notion, MS Word)
  • Game save systems
  • State restoration in visual editors (like Figma, Canva)
  • Transaction rollback systems
  • Form editing with preview/reset options

To summarize, it would be apt to say,

The Memento Pattern lets your objects “remember” and “rewind” their states, just like a time machine, enabling undo functionality without exposing their inner workings.

It is the design pattern equivalent of Ctrl+Z. It gives you the power to undo mistakes or revisit past states without complicating your logic or breaking encapsulation.

Hope, the next time you hit the UNDO/REDO on your keyboard, you will definitely recall this pattern.

Next up in the series: Template Pattern. Stay tuned!


This content originally appeared on DEV Community and was authored by Prateek Prabhakar