Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Py

Python

Readable, batteries-included, and the default language of AI.

Paradigm
Multi-paradigm, OOP, functional
Typing
Dynamic, strong, optional type hints
Memory
Reference counting + cycle GC
Runs
CPython bytecode interpreter
Concurrency
asyncio, threads (GIL), multiprocessing
Behavioral pattern

Memento

Intent

Saves and restores an object's previous state without revealing its implementation.

Problem

An editor needs undo, but snapshotting requires access to private fields.

Solution

The originator produces snapshot objects itself; a caretaker stores them.

Real-world analogy

Think of it like this

Saving your game before the boss fight, so you can reload if things go wrong.

Structure

association / extends implements / depends on
Originator - state+ save(): Memento+ restore(m: Memento) 1 Memento - state+ getState() 2 Caretaker - originator- history: Memento[]+ doSomething()+ undo() 3

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Originator — Originator produces snapshots of its own state and restores from them.
  2. 2Memento — Memento is an immutable snapshot of the originator's state.
  3. 3Caretaker — Caretaker knows when to capture and restore, and keeps a history stack.

Code example

A Python code sample for Memento is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Memento when undo / snapshots.

Use Memento when direct access to fields would break encapsulation.

Pros and cons

Pros

  • Snapshots without breaking encapsulation

Cons

  • Memory use with frequent snapshots

Relations with other patterns

Check yourself

Check yourself

A form editor must restore its previous state when the user presses Cancel.

Saved in this browser only. Part of Behavioral patterns (0/11).