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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)