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.
An undoable command records enough information to restore its input state when applied immediately after its corresponding edit. In a sequence, insertion at index is reversed by deletion at ; deletion is reversed by reinsertion of the saved value. If a move places an entry at final index after removing it from index , the inverse moves it from back to . Removing the moved entry recovers the original sequence with exactly that entry missing, which proves the inverse for both directions and for .
These local inverse identities extend to a history by applying inverses in reverse chronological order. A stack of completed commands and a stack of undone commands maintain that order. A fresh command invalidates the old redo branch. Arbitrary inverses after unrelated intervening edits need not satisfy the restoration identity. State snapshots in the Memento pattern supply a different way to realize the same chronological undo/redo contract.
Articles by others on the same topic
There are currently no matching articles.