SOLID & Design Patterns Interview Question #45

What is the Memento Pattern?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

The Memento Pattern captures an object's internal state so it can be restored later without exposing all of its internal implementation. It is commonly associated with undo, snapshots, or rollback of in-memory state.

Detailed Explanation

The Memento Pattern captures an object's internal state so it can be restored later without exposing all of its internal implementation. It is commonly associated with undo, snapshots, or rollback of in-memory state.

Memento can consume substantial memory when snapshots are large. For persistent business data, database transactions, event sourcing, or audit history may be more appropriate depending on the requirement.

Code Example

public record EditorMemento(string Text);

public class Editor
{
    public string Text { get; set; } = "";

    public EditorMemento Save()
        => new(Text);

    public void Restore(EditorMemento memento)
        => Text = memento.Text;
}