Command Pattern: Definition & Core Concept
The Command Pattern turns requests into standalone objects that contain all information about the request. This transformation lets you pass requests as method arguments, delay or queue request execution, and implement reversible operations.
Core Problem Solved
Without Command Pattern, application logic becomes tightly coupled to UI elements. A Button directly calls document.save(), making it impossible to reuse the save logic elsewhere, create keyboard shortcuts, implement undo functionality, or queue operations. The pattern solves this by decoupling the object that invokes the operation from the one that performs it.
When You Need It
First, you need undo/redo functionality where operations must be reversible. Second, you want to queue operations for later execution or log them for audit trails. Third, you have multiple UI elements (buttons, menu items, keyboard shortcuts) that trigger the same operation. Fourth, you need to implement macro recording where complex sequences of actions can be saved and replayed. If none of these apply, direct method calls are simpler and appropriate instead.