DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

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 };
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:

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM appsโ€”no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

๐Ÿ‘‹ Kindness is contagious

Dive into this insightful article, celebrated by the caring DEV Community. Programmers from all walks of life are invited to share and expand our collective wisdom.

A simple thank-you can make someoneโ€™s dayโ€”drop your kudos in the comments!

On DEV, spreading knowledge paves the way and strengthens our community ties. If this piece helped you, a brief note of appreciation to the author truly counts.

Letโ€™s Go!