Skip to content

Memento

A pattern that saves and restores internal object state as encapsulated snapshots.

  • When implementing checkpoint rollback.
  • When supporting Undo / Redo.
  • Originator
  • Memento
  • Caretaker

The code below is a simplified Unity example based on the scenario described above.

using System.Collections.Generic;
using UnityEngine;
public readonly struct PlayerStateSnapshot
{
public readonly Vector3 Position;
public readonly int Health;
public PlayerStateSnapshot(Vector3 position, int health)
{
Position = position;
Health = health;
}
}
public sealed class PlayerStateHistory
{
private readonly Stack<PlayerStateSnapshot> snapshots = new();
public void Save(PlayerStateSnapshot snapshot) => snapshots.Push(snapshot);
public bool TryRestore(out PlayerStateSnapshot snapshot) => snapshots.TryPop(out snapshot);
}
  • State save and restore logic can be isolated without exposing internal details.
  • It works well for checkpoint and history-based systems.
  • Snapshot data can grow quickly if the state is large.
  • If restore timing is not clearly defined, synchronization bugs can occur.

This shows the flow where original state is stored as a snapshot and restored when needed.

Memento Flow