Design Patterns

Pattern 17 of 23, Behavioral family

Memento

Also known as: Token

Capture and later restore an object's internal state without violating its encapsulation.

The problem

Undo requires saving an editor's state. But its fields are private: copying them from the outside breaks encapsulation and couples the history to the internal structure.

The solution

The object (originator) produces an opaque snapshot itself, the Memento. A caretaker (history) stores these snapshots without ever reading their content, then hands them back to restore.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The caretaker asks for a snapshot.
  2. Only the Editor knows how to create (and read back) its memento.
  3. The history stores an opaque object.
  4. The user edits the textโ€ฆ and breaks everything.
  5. History [v1] โ†’ Memento "v1": pop()
  6. State restored, without exposing the Editor's internals.

An analogy

A video game save: you can load it later without knowing how the game encodes its state.

When to use it

  • Undo / redo, save points
  • Transactions and rollback
  • Drafts, auto-save

Pros and cons

Pros

  • Encapsulation preserved
  • Simpler originator: history is managed elsewhere

Cons

  • Memory usage when snapshots are frequent and heavy
  • The caretaker has to manage the mementos' lifecycle

Implementations

The same example, written idiomatically in each language.

Memento in Python

memento.py 30 lines
from dataclasses import dataclass


@dataclass(frozen=True)
class Memento:
    _text: str
    _cursor: int


class Editor:
    def __init__(self):
        self.text, self.cursor = "", 0

    def type(self, s: str):
        self.text += s
        self.cursor = len(self.text)

    def save(self) -> Memento:
        return Memento(self.text, self.cursor)

    def restore(self, m: Memento):
        self.text, self.cursor = m._text, m._cursor


ed, history = Editor(), []
ed.type("v1")
history.append(ed.save())
ed.type(" + bug")
ed.restore(history.pop())
print(ed.text)   # v1

Memento in TypeScript

memento.ts 24 lines
class Memento {
  constructor(readonly text: string, readonly cursor: number) {
    Object.freeze(this);
  }
}

class Editor {
  private text = "";
  private cursor = 0;

  type(s: string) {
    this.text += s;
    this.cursor = this.text.length;
  }
  save() { return new Memento(this.text, this.cursor); }
  restore(m: Memento) { this.text = m.text; this.cursor = m.cursor; }
}

const ed = new Editor();
const history: Memento[] = [];
ed.type("v1");
history.push(ed.save());
ed.type(" + bug");
ed.restore(history.pop()!);

Memento in Java

memento.java 18 lines
class Editor {
    private String text = "";
    private int cursor;

    // nested, immutable record: the snapshot
    public record Memento(String text, int cursor) {}

    void type(String s) { text += s; cursor = text.length(); }

    Memento save() { return new Memento(text, cursor); }

    void restore(Memento m) { text = m.text(); cursor = m.cursor(); }
}

Deque<Editor.Memento> history = new ArrayDeque<>();
history.push(editor.save());
editor.type(" + bug");
editor.restore(history.pop());

Memento in C#

memento.cs 18 lines
public class Editor
{
    private string _text = "";
    private int _cursor;

    public sealed record Memento(string Text, int Cursor);

    public void Type(string s) { _text += s; _cursor = _text.Length; }

    public Memento Save() => new(_text, _cursor);

    public void Restore(Memento m) => (_text, _cursor) = (m.Text, m.Cursor);
}

var history = new Stack<Editor.Memento>();
history.Push(editor.Save());
editor.Type(" + bug");
editor.Restore(history.Pop());

Memento in PHP

memento.php 29 lines
final class EditorMemento
{
    public function __construct(
        public readonly string $text,
        public readonly int $cursor,
    ) {}
}

final class Editor
{
    private string $text = '';
    private int $cursor = 0;

    public function type(string $s): void
    {
        $this->text .= $s;
        $this->cursor = strlen($this->text);
    }

    public function save(): EditorMemento
    {
        return new EditorMemento($this->text, $this->cursor);
    }

    public function restore(EditorMemento $m): void
    {
        [$this->text, $this->cursor] = [$m->text, $m->cursor];
    }
}

Memento in Go

memento.go 20 lines
type Memento struct {
    text   string // unexported fields: opaque outside the package
    cursor int
}

type Editor struct {
    text   string
    cursor int
}

func (e *Editor) Type(s string)     { e.text += s; e.cursor = len(e.text) }
func (e *Editor) Save() Memento     { return Memento{e.text, e.cursor} }
func (e *Editor) Restore(m Memento) { e.text, e.cursor = m.text, m.cursor }

var history []Memento

history = append(history, ed.Save())
ed.Type(" + bug")
ed.Restore(history[len(history)-1])
history = history[:len(history)-1]

Frequently asked questions

What is the Memento design pattern?

Capture and later restore an object's internal state without violating its encapsulation. The object (originator) produces an opaque snapshot itself, the Memento. A caretaker (history) stores these snapshots without ever reading their content, then hands them back to restore.

When should you use the Memento pattern?

Undo / redo, save points; Transactions and rollback; Drafts, auto-save.

What are the pros and cons of the Memento pattern?

Pros: Encapsulation preserved; Simpler originator: history is managed elsewhere. Cons: Memory usage when snapshots are frequent and heavy; The caretaker has to manage the mementos' lifecycle.