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:

Heroku

Amplify your impact where it matters most โ€” building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. โค๏ธ