Memento

Captures and externalizes an object's internal state without violating its encapsulation.

Context

A text/image editor needs an undo mechanism. The state is complex (selection, history, buffers).

Problem

Exposing the internal state for external saving breaks encapsulation.

Solution

The object produces an opaque Memento for external use; only the object itself knows how to restore its state from one.

#Example in C#

public class Editor
{
    private string _content = "";

    public Memento Save() => new(_content);
    public void Restore(Memento m) => _content = m.State;

    public class Memento
    {
        internal string State { get; }
        internal Memento(string s) => State = s;
    }
}
Tradeoffs
Pro Con
Preserves encapsulation Can consume significant memory

#behavioral #gof #snapshot