Memento
Memento
Section titled “Memento”One-line pattern summary
Section titled “One-line pattern summary”A pattern that saves and restores internal object state as encapsulated snapshots.
Typical Unity use cases
Section titled “Typical Unity use cases”- When implementing checkpoint rollback.
- When supporting Undo / Redo.
Parts (roles)
Section titled “Parts (roles)”- Originator
- Memento
- Caretaker
Unity example (C#)
Section titled “Unity example (C#)”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);}Advantages
Section titled “Advantages”- State save and restore logic can be isolated without exposing internal details.
- It works well for checkpoint and history-based systems.
Things to watch out for
Section titled “Things to watch out for”- Snapshot data can grow quickly if the state is large.
- If restore timing is not clearly defined, synchronization bugs can occur.
Interaction diagram
Section titled “Interaction diagram”This shows the flow where original state is stored as a snapshot and restored when needed.