DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Behavioral - Command

Image description

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 };
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)