Member-only story
The command pattern is an incredibly useful JavaScript design pattern for decoupling method logic into standalone classes. This makes code more extensible, easier to test, and allows flexible implementations like queues, logging, and undo/redo.
In this article we’ll break down what the command pattern is and some ways it can help streamline your code.
What is the Command Pattern?
The command pattern encapsulates method logic into separate objects called command objects. These command objects expose a common interface to execute the methods.
Here is a simple command object example:
class TurnOnLightCommand {
constructor(light) {
this.light = light;
}
execute() {
this.light.turnOn();
}
}
let light = new SmartLight();
let command = new TurnOnLightCommand(light);
command.execute(); // Executes light.turnOn();
The key benefit is decoupling the class that invokes the method from the object that actually executes the method.