Course contentsShow
← Software Engineering
Lesson 292 of 1,9339. Behavioral Design PatternsFree lesson

Undo and Redo with Command Pattern

Storing command history and implementing reversible operations.

Undo and Redo with Command Pattern

What you'll learn: How storing executed commands enables powerful undo/redo functionality in your applications.

The Core Idea

Once you've encapsulated operations as command objects (from the previous lesson), you can store them in a history stack. Each executed command gets pushed onto this stack. When the user wants to undo, you pop the most recent command and call its undo() method. For redo, you maintain a separate stack of undone commands and re-execute them when needed.

Analogy: Think of a text editor's undo feature. Every action you take (typing, deleting, formatting) is like a command card placed on a stack. Hitting "undo" picks up the top card and reverses what it says. The card then moves to a "redo pile" in case you change your mind.

How It Works

When a command executes successfully:

  1. Store the command object in an "undo stack"
  2. Clear any existing "redo stack" (new actions invalidate future redos)

For undo:

  1. Pop the most recent command from the undo stack
  2. Call its undo() method to reverse the operation
  3. Push this command onto the redo stack

For redo:

  1. Pop a command from the redo stack
  2. Call its execute() method again
  3. Push it back onto the undo stack

Why This Matters

This pattern requires that commands store enough state to reverse themselves. For example, a "DeleteText" command must remember what was deleted and where, so it can restore it during undo.

Key Takeaway: By maintaining history stacks of command objects with reversible operations, you transform simple actions into a full undo/redo system—all because commands are first-class, storable objects.