Article · Memento
Memento: a state snapshot without breaking encapsulation
The Memento pattern through a menu editor: Halina saves versions of the menu and returns to them with one click, while the history keeps snapshots without seeing what is inside. Copies instead of references, memory costs and code in five languages.
Halina is putting together the autumn menu in the admin panel. She raises prices, adds pierogi with black pudding, deletes the potato-and-cheese ones by mistake – and wants to go back to the version from five minutes ago. Memento lets you save a snapshot of an object's state and restore it later, while nobody but the object itself looks inside.
- 3
- roles in the pattern – originator, memento, caretaker
- 0
- menu fields visible to the history – only a label and the save time
- 1
- typical bug – a snapshot sharing a collection with the original
The problem: a history that knows too much
The first version of the editor kept copies of the menu draft in an array:
class MenuDraft {
title = 'Autumn menu';
prices = new Map<string, number>(); // public, so the editor can copy it
}
const versions: { title: string; prices: Map<string, number> }[] = [];
function saveVersion(draft: MenuDraft): void {
versions.push({ title: draft.title, prices: draft.prices }); // bug: same Map, not a copy
}
function undo(draft: MenuDraft): void {
const last = versions.pop();
if (last) Object.assign(draft, last); // the editor knows every field of the draft
}There are two problems here. First, the editor knows every field of the draft (title, prices), so every new field – a photo, allergens, the order of dishes – requires changes in the history. The draft also has to expose its fields publicly, just so they can be copied. Second, the "copy" is a reference to the same price map: every later change to the draft silently changes the saved versions too, so undo restores… the current state.
The solution: let the object take its own pictures
The menu draft (the originator) gets two methods: save(label) creates a snapshot, and restore(snapshot) restores the state from it. The snapshot contains a copy of everything the draft needs to rebuild itself, but exposes only a label and the save time to the outside. The history (the caretaker) keeps a stack of snapshots and hands them back to the draft on request – without understanding what is inside.
| Role | In the example | Responsibility |
|---|---|---|
| Originator | MenuDraft | creates a snapshot of its state and restores itself from it |
| Memento | Snapshot behind the MenuSnapshot interface | an immutable copy of the state; only metadata on the outside |
| Caretaker | MenuHistory | stores snapshots, decides when to save and undo |
Implementation in five languages
The most interesting part is how each language hides the snapshot's contents. C# and Java use a private nested type behind a public interface. TypeScript keeps the state in the module, in a WeakMap only the draft can access. Go relies on package-level encapsulation (lower-case fields), and Python on the underscore convention and an immutable copy.
Memento – menu editor
var draft = new MenuDraft("Autumn menu");
var menuHistory = new MenuHistory(draft);
draft.SetPrice("Ruskie", 28m);
menuHistory.Save("base prices");
draft.SetPrice("Ruskie", 32m);
draft.SetPrice("With black pudding", 35m);
menuHistory.Save("price rise");
draft.Remove("Ruskie"); // oops
menuHistory.Undo(); // back to "price rise"
Console.WriteLine(draft); // Autumn menu: Ruskie 32, With black pudding 35
// All the caretaker may see: a label and a time, never the menu itself.
public interface IMenuSnapshot
{
string Label { get; }
DateTime TakenAt { get; }
}
public sealed class MenuDraft(string title)
{
private string _title = title;
private readonly Dictionary<string, decimal> _prices = new();
public void SetPrice(string dish, decimal price) => _prices[dish] = price;
public void Remove(string dish) => _prices.Remove(dish);
// Copy the dictionary – a snapshot must not share mutable state with the draft.
public IMenuSnapshot Save(string label) => new Snapshot(label, DateTime.UtcNow, _title, new(_prices));
public void Restore(IMenuSnapshot snapshot)
{
var s = (Snapshot)snapshot; // only the originator knows the real type
_title = s.Title;
_prices.Clear();
foreach (var (dish, price) in s.Prices) _prices[dish] = price;
}
public override string ToString() => $"{_title}: {string.Join(", ", _prices.Select(p => $"{p.Key} {p.Value}"))}";
// Nested and private: nobody outside MenuDraft can read the saved state.
private sealed record Snapshot(string Label, DateTime TakenAt, string Title, Dictionary<string, decimal> Prices)
: IMenuSnapshot;
}
// The caretaker stores snapshots without looking inside.
public sealed class MenuHistory(MenuDraft draft)
{
private readonly Stack<IMenuSnapshot> _snapshots = new();
public void Save(string label) => _snapshots.Push(draft.Save(label));
public void Undo()
{
if (_snapshots.TryPop(out var snapshot)) draft.Restore(snapshot);
}
}type MenuState = { title: string; prices: Map<string, number> };
/** Opaque handle: the caretaker sees only a label and a time. */
interface MenuSnapshot {
readonly label: string;
readonly takenAt: Date;
}
// Module-private storage: only MenuDraft can turn a snapshot back into state.
const saved = new WeakMap<MenuSnapshot, MenuState>();
class MenuDraft {
private prices = new Map<string, number>();
constructor(private title: string) {}
setPrice(dish: string, price: number): void { this.prices.set(dish, price); }
remove(dish: string): void { this.prices.delete(dish); }
save(label: string): MenuSnapshot {
const snapshot = Object.freeze({ label, takenAt: new Date() });
saved.set(snapshot, { title: this.title, prices: new Map(this.prices) }); // copy, not a reference
return snapshot;
}
restore(snapshot: MenuSnapshot): void {
const state = saved.get(snapshot);
if (!state) throw new Error('Unknown snapshot');
this.title = state.title;
this.prices = new Map(state.prices);
}
toString(): string {
return `${this.title}: ${[...this.prices].map(([d, p]) => `${d} ${p}`).join(', ')}`;
}
}
class MenuHistory {
private readonly snapshots: MenuSnapshot[] = [];
constructor(private readonly draft: MenuDraft) {}
save(label: string): void { this.snapshots.push(this.draft.save(label)); }
undo(): void {
const snapshot = this.snapshots.pop();
if (snapshot) this.draft.restore(snapshot);
}
}
const draft = new MenuDraft('Autumn menu');
const menuHistory = new MenuHistory(draft);
draft.setPrice('Ruskie', 28);
menuHistory.save('base prices');
draft.setPrice('Ruskie', 32);
draft.setPrice('With black pudding', 35);
menuHistory.save('price rise');
draft.remove('Ruskie'); // oops
menuHistory.undo();
console.log(draft.toString()); // Autumn menu: Ruskie 32, With black pudding 35import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.Map;
// All the caretaker may see: a label and a time, never the menu itself.
interface MenuSnapshot {
String label();
Instant takenAt();
}
class MenuDraft {
private String title;
private final Map<String, Integer> prices = new LinkedHashMap<>();
MenuDraft(String title) { this.title = title; }
void setPrice(String dish, int price) { prices.put(dish, price); }
void remove(String dish) { prices.remove(dish); }
// Private nested record: only MenuDraft can read the saved state.
private record Snapshot(String label, Instant takenAt, String title, Map<String, Integer> prices)
implements MenuSnapshot {}
MenuSnapshot save(String label) {
return new Snapshot(label, Instant.now(), title, new LinkedHashMap<>(prices)); // copy!
}
void restore(MenuSnapshot snapshot) {
var s = (Snapshot) snapshot;
title = s.title();
prices.clear();
prices.putAll(s.prices());
}
@Override public String toString() { return title + ": " + prices; }
}
// The caretaker stores snapshots without looking inside.
class MenuHistory {
private final Deque<MenuSnapshot> snapshots = new ArrayDeque<>();
private final MenuDraft draft;
MenuHistory(MenuDraft draft) { this.draft = draft; }
void save(String label) { snapshots.push(draft.save(label)); }
void undo() { if (!snapshots.isEmpty()) draft.restore(snapshots.pop()); }
}
public class MenuEditor {
public static void main(String[] args) {
var draft = new MenuDraft("Autumn menu");
var menuHistory = new MenuHistory(draft);
draft.setPrice("Ruskie", 28);
menuHistory.save("base prices");
draft.setPrice("Ruskie", 32);
draft.setPrice("With black pudding", 35);
menuHistory.save("price rise");
draft.remove("Ruskie"); // oops
menuHistory.undo();
System.out.println(draft); // Autumn menu: {Ruskie=32, With black pudding=35}
}
}package main
import (
"fmt"
"maps"
"time"
)
// Snapshot has only unexported state fields: code outside this package
// (e.g. a caretaker in another package) can store it but not read the menu.
type Snapshot struct {
Label string
TakenAt time.Time
title string
prices map[string]int
}
type MenuDraft struct {
title string
prices map[string]int
}
func NewMenuDraft(title string) *MenuDraft {
return &MenuDraft{title: title, prices: map[string]int{}}
}
func (m *MenuDraft) SetPrice(dish string, price int) { m.prices[dish] = price }
func (m *MenuDraft) Remove(dish string) { delete(m.prices, dish) }
// Save copies the map – a snapshot must not share mutable state with the draft.
func (m *MenuDraft) Save(label string) Snapshot {
return Snapshot{label, time.Now(), m.title, maps.Clone(m.prices)}
}
func (m *MenuDraft) Restore(s Snapshot) {
m.title, m.prices = s.title, maps.Clone(s.prices)
}
// MenuHistory is the caretaker.
type MenuHistory struct {
draft *MenuDraft
snapshots []Snapshot
}
func (h *MenuHistory) Save(label string) { h.snapshots = append(h.snapshots, h.draft.Save(label)) }
func (h *MenuHistory) Undo() {
if n := len(h.snapshots); n > 0 {
h.draft.Restore(h.snapshots[n-1])
h.snapshots = h.snapshots[:n-1]
}
}
func main() {
draft := NewMenuDraft("Autumn menu")
menuHistory := &MenuHistory{draft: draft}
draft.SetPrice("Ruskie", 28)
menuHistory.Save("base prices")
draft.SetPrice("Ruskie", 32)
draft.SetPrice("With black pudding", 35)
menuHistory.Save("price rise")
draft.Remove("Ruskie") // oops
menuHistory.Undo()
fmt.Println(draft.title, draft.prices) // Autumn menu map[Ruskie:32 With black pudding:35]
}from dataclasses import dataclass, field
from datetime import datetime, timezone
from types import MappingProxyType
from typing import Mapping
@dataclass(frozen=True)
class MenuSnapshot:
"""The caretaker should only use label and taken_at; the rest is the originator's business."""
label: str
taken_at: datetime
_title: str = field(repr=False)
_prices: Mapping[str, int] = field(repr=False)
class MenuDraft:
def __init__(self, title: str) -> None:
self._title = title
self._prices: dict[str, int] = {}
def set_price(self, dish: str, price: int) -> None:
self._prices[dish] = price
def remove(self, dish: str) -> None:
self._prices.pop(dish, None)
def save(self, label: str) -> MenuSnapshot:
# Copy and freeze: the snapshot must not share mutable state with the draft.
frozen = MappingProxyType(dict(self._prices))
return MenuSnapshot(label, datetime.now(timezone.utc), self._title, frozen)
def restore(self, snapshot: MenuSnapshot) -> None:
self._title = snapshot._title
self._prices = dict(snapshot._prices)
def __str__(self) -> str:
return f"{self._title}: " + ", ".join(f"{d} {p}" for d, p in self._prices.items())
class MenuHistory:
"""The caretaker stores snapshots without looking inside."""
def __init__(self, draft: MenuDraft) -> None:
self._draft = draft
self._snapshots: list[MenuSnapshot] = []
def save(self, label: str) -> None:
self._snapshots.append(self._draft.save(label))
def undo(self) -> None:
if self._snapshots:
self._draft.restore(self._snapshots.pop())
draft = MenuDraft("Autumn menu")
menu_history = MenuHistory(draft)
draft.set_price("Ruskie", 28)
menu_history.save("base prices")
draft.set_price("Ruskie", 32)
draft.set_price("With black pudding", 35)
menu_history.save("price rise")
draft.remove("Ruskie") # oops
menu_history.undo()
print(draft) # Autumn menu: Ruskie 32, With black pudding 35The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- What does the history cost?
- Memento vs undo through Command
- When to use it and when not to
- Related patterns
- In practice
- Test yourself