Skip to main content

Command Palette

Search for a command to run...

JavaScript Design Patterns - Behavioral - Command

Updated
•1 min read•View as Markdown
N

I'm Nhan. I'm a web developer from Vietnam. I have over 5 years of experience in the Angular framework.

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:

More from this blog

Nhan Nguyen's blog

88 posts

I’m a web developer, and I am really passionate about learning web development.