Command
Last updated
Last updated
Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request.
This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.
The Command design pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations.
This pattern enables the separation of concerns between sender and receiver of a command, allowing for greater flexibility and extensibility in code.
In JavaScript, you can implement the Command pattern using objects that represent commands and invokers that execute those commands.
In this example:
We have a Command
interface which defines the execute
method.
Concrete commands (LightOnCommand
and LightOffCommand
) implement the Command
interface and encapsulate the actions to be performed on the receiver (Light
).
Light
acts as the receiver of the commands.
RemoteControl
serves as the invoker, which sets and executes commands.
This pattern allows for decoupling of the sender (invoker) from the receiver, making it easy to extend and modify behavior without affecting other parts of the code.