The Command pattern encapsulates requests as objects, decoupling the invoker (which triggers the request) from the receiver (which performs the action). By wrapping a request's details, such as the operation, receiver, and parameters, into a command object, the invoker doesn't need to know how the receiver processes the request, promoting loose coupling and flexibility. This encapsulation enables advanced features like undo operations, where a command object stores the necessary state or logic to reverse its action. It also supports queuing, allowing commands to be stored and executed later in a controlled manner, and macro operations, where multiple commands can be grouped into a single composite command for execution as a unit. These capabilities make the Command pattern ideal for systems requiring flexible, reversible, or scheduled operations.
The Command pattern encapsulates a request as an object. This lets you parameterize invokers with different actions, queue or log requests, compose macro commands, and support undo/redo— while keeping senders (invokers) independent of receivers.
execute()), ConcreteCommand (stores a
receiver and implements execute()), Receiver (business logic), Invoker (triggers
execute()), Client (wires everything).execute() → ConcreteCommand calls receiver.action().
Command, not concrete receivers.unexecute() and keep prior state.execute() off-thread with retries/backoff.See the runnable example with Invoker, Receiver, and multiple ConcreteCommand classes: Command Pattern in Java (code)