The Memento Pattern provides the ability to restore an object to its previous state (undo via rollback). It captures and externalizes an object's internal state without violating Encapsulation. The object itself is the only one who knows how to "read" the state back.
If you have 50 private fields, a "Zapper" class shouldn't have to know about all of them to save a backup. The Memento pattern creates a tiny "Snapshot" object that only the original class understands.
public class Editor
{
private string _content;
public Memento Save() => new Memento(_content);
public void Restore(Memento m) => _content = m.GetContent();
}
public class Memento // Immutable snapshot
{
private readonly string _state;
public Memento(string s) => _state = s;
public string GetContent() => _state;
}
In a game engine, when you hit "Quick Save," the engine takes a Memento of the Player, the NPCs, and the World. When you die, it feeds those Mementos back into the objects to reset their HP, position, and inventory.
Q: "How is the Memento pattern different from simple Serialization?"
Architect Answer: "Intent and Encapsulation. **Serialization** is used to convert an object into a transferrable format (JSON/XML) for storage or transmission. **Memento** is used specifically to capture an 'In-Memory Snapshot' for the purpose of undoing a current operation. Memento protects encapsulation by ensuring that no other class can see or modify the snapshotted state; it is a 'Black Box' to everyone except the creator."