Sitemap
Anant Nema

Anant Nema

Command Pattern

2 min readJul 22, 2024

The Command Pattern is a behavioral design pattern that encapsulates a request as an object, allowing us to decouple the requester of the command from the object that executes the command. By doing so, it enables us to queue commands, log them, or even undo them.

In JavaScript, the Command Pattern is often used to encapsulate user actions that can be executed, undone, or redone. The pattern involves defining a command class that contains the action to be executed and the receiver object that performs the action.

Here’s an example of how the Command Pattern can be implemented in JavaScript:

// Receiver object that performs the actions
class Light {
turnOn() {
console.log('The light is on.');
}
turnOff() {
console.log('The light is off.');
}
}

// Command class that encapsulates the request as an object
class LightCommand {
constructor(light, action) {
this.light = light;
this.action = action;
}
execute() {
this.light[this.action]();
}
}

// Invoker object that executes the commands
class RemoteControl {
constructor() {
this.commands = [];
}

addCommand(command) {
this.commands.push(command);
}

executeCommands() {
this.commands.forEach(command => {
command.execute();
});
}
}

// Using the Command Pattern to turn on and off the light
const light = new Light();
const turnOnCommand = new LightCommand(light, 'turnOn');
const turnOffCommand = new LightCommand(light, 'turnOff');

const remoteControl = new RemoteControl();
remoteControl.addCommand(turnOnCommand);
remoteControl.addCommand(turnOffCommand);
remoteControl.executeCommands();

In this example, we have defined a

Light

class that represents an object that can turn on and off. We then define a

LightCommand

class that encapsulates the request to turn on or off the light, and the receiver object, which is an instance of the

Light

class.

Get Anant Nema’s stories in your inbox

Join Medium for free to get updates from this writer.

We then define an

Invoker

class called

RemoteControl

, which accepts a list of commands and executes them in sequence.

Finally, we create an instance of the

Light

class, create two instances of the

LightCommand

class that represent turning on and off the light, add them to the instance of the

RemoteControl

class, and invoke the

executeCommands()

method to execute the commands.

This allows us to decouple the requester of the command from the object that executes the command, making it possible to execute multiple commands in a sequence, log the commands, undo the commands, or even redo the commands.

--

--