intermediateCommand Pattern

The basic Command interface only has an execute() method. What has to change to support undo?

The Command interface needs a second method, typically undo(), that every concrete command also implements. More importantly, a concrete command usually has to capture whatever state is needed to reverse itself at the moment execute() actually runs, not afterward when undo() is eventually called, because the state needed to reverse the action may no longer be available or correct by that later point. For a bold-toggling command, that might mean recording whether the text was already bold before execute() ran, so undo() can restore that exact prior state rather than guessing. This is structurally the same problem the Memento pattern solves — capturing state before a change so it can be restored later — and the two patterns are frequently combined: a command's undo() implementation stores or uses a memento of the receiver's state.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What's the difference between an abstract method and a hook method in the Template Method pattern?← Back to all Low-Level Design & Design Patterns questions