JavaScript Design Patterns - Behavioral - Command
The command pattern allows encapsulating a request as an object. This transformation lets you pass requests as method arguments, delay or queue a request’s execution, and support undoable operations.
In the below example, we encapsulate the on/off instructions as objects and pass them as arguments in the Car constructor.
class Car {
constructor(instruction) {
this.instruction = instruction;
}
execute() {
this.instruction.execute();
}
}
class Engine {
constructor() {
this.state = false;
}
on() {
this.state = true;
}
off() {
this.state = false;
}
}
class OnInstruction {
constructor(engine) {
this.engine = engine;
}
execute() {
this.engine.on();
}
}
class OffInstruction {
constructor(engine) {
this.engine = engine;
}
execute() {
this.engine.off();
}
}
export { Car, Engine, OnInstruction, OffInstruction };
A complete example is here https://stackblitz.com/edit/vitejs-vite-ejmk6g?file=main.js
👉 Use this pattern when we have a queue of requests to handle or if we want to have an undo action.
I hope you found it helpful. Thanks for reading. 🙏
Let’s get connected! You can find me on:
Hashnode: https://nhannguyen.hashnode.dev/
X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Buy Me a Coffee:https://www.buymeacoffee.com/nhannguyendevjs