Command pattern (source code)

= Command pattern
{wiki}

Represent a request and the information needed to execute it as a <software object> with a common command interface. Undoable commands additionally retain enough information to invert their change: an insertion retains its position and value, a deletion retains the removed value, and a positional move retains the source and final destination indices.

For sequential undo/redo, a history manager stores applied commands on one <stack> and undone commands on another. Undo transfers the most recent applied command to the redo <stack>; redo transfers its head back after reapplying it. A fresh edit clears the redo branch. Command inverses are valid under this chronological protocol, not generally after unrelated intervening edits. Saving complete immutable versions instead gives a <Memento pattern> implementation of the same undo/redo interface.