What is the Command pattern and how is it used?
TL;DR
The Command pattern is a behavioral design pattern that turns a request into a stand-alone object containing all information about the request. This transformation allows for parameterization of methods with different requests, queuing of requests, and logging of requests. It also supports undoable operations. In JavaScript, it can be implemented by creating command objects with execute and undo methods.
Encapsulating a request as an object
A command separates the code that requests an action from the receiver that knows how to perform it.
Because the request is a value, an invoker can queue, log, retry, compose, or undo commands without understanding receiver details.
Definition
The Command pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with queues, requests, and operations. It also provides support for undoable operations.
Components
- Command: Declares an interface for executing an operation.
- ConcreteCommand: Implements the
executemethod by invoking the corresponding operation(s) onReceiver. - Receiver: Knows how to perform the operations associated with carrying out a request.
- Invoker: Asks the command to carry out the request.
- Client: Creates a
ConcreteCommandobject and sets its receiver.
Implementation in JavaScript
Use cases
- Undo/Redo functionality: The Command pattern is ideal for implementing undo and redo operations.
- Macro commands: It can be used to implement a sequence of commands.
- Logging changes: It helps in logging changes and auditing them later.
- GUI buttons and menu items: It is useful for implementing actions triggered by GUI elements.