Open In App

Command Method | JavaScript Design Patterns

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The command method is a behavioral design pattern that encapsulates an incoming request into a standalone object. This object contains all the necessary information to perform a request including the method to call and parameters.

Why do the we use Command Method?

The Command Method is needed to separate the sender information of the request and the object that processes the request. It promotes loose coupling, reusability, and flexibility in handling commands by turning requests into standalone objects. So, the objects can be processed or executed by the different parts of the application.

Command Method example in JavaScript Design Patterns

problem statement

We will implement control of a light bulb’s state (On or Off) using an organized and flexible structure. The system should allow the client to interact with the light bulb via commands and provide a simple and efficient way to switch the light on and off.

Implementation of Command Method using JavaScript:

1. Creation of Command class

Note: JavaScript doesn’t support Interfaces directly. Create a class with empty implementation and override the method in other class.

Javascript




class Command {
  execute() {}
}


In this step, We have created the command class which contains the declaration of the execute method.

2. Creation of Concrete Command class

Javascript




class OnCommand extends Command {
  constructor(lightBulb) {
    super();
    this.lightBulb = lightBulb;
  }
 
  execute() {
    this.lightBulb.on();
  }
}
 
class OffCommand extends Command {
  constructor(lightBulb) {
    super();
    this.lightBulb = lightBulb;
  }
 
  execute() {
    this.lightBulb.off();
  }
}



3. Creation of Receiver

In this step, We have created two classes namely `OnCommand` and `OffCommand` which extend the `Command` class. Each class contains a variable `lightBulb` which holds the information i.e. `On` or `Off ` status. These classes override the `execute` method of the command class and define it with command-specific implementation.

Javascript




class LightBulb {
  on() {
    console.log('Bulb is ON');
  }
 
  off() {
    console.log('Bulb is OFF');
  }
}


4. Creation of Invoker

In this step, We have created the `Receiver` class which is `LightBulb`, which contains the actual implementation of the `on` and `off` methods.

Javascript




class Switch {
  constructor() {
    this.command = null;
  }
 
  setCommand(command) {
    this.command = command;
  }
 
  executeCommand() {
    this.command.execute();
  }
}



In this step, We have created the Invoker which is a `Switch` class that defines a constructor that initializes the command to a null value at first. The Switch class defines two methods namely `setCommand` and `executeCommand` whose purpose is to set the command (on or off) and execute the command (the console logs the information).

5. Usage and Client code

The client code interacts with the `Concrete Command` class, `Receiver` and `Invoker`. The `Invoker (Switch)` sets the command and executes the command accordingly.

Javascript




const light = new LightBulb();
const on = new OnCommand(light);
const off = new OffCommand(light);
 
const switchButton = new Switch();
 
switchButton.setCommand(On);
switchButton.executeCommand();
 
switchButton.setCommand(off);
switchButton.executeCommand();


Below is the complete combined code for the above example:

Javascript




class Command {
  execute() {}
}
class OnCommand extends Command {
  constructor(lightBulb) {
    super();
    this.lightBulb = lightBulb;
  }
 
  execute() {
    this.lightBulb.On();
  }
}
 
class OffCommand extends Command {
  constructor(lightBulb) {
    super();
    this.lightBulb = lightBulb;
  }
 
  execute() {
    this.lightBulb.Off();
  }
}
class LightBulb {
  On() {
    console.log('Bulb is ON');
  }
 
  Off() {
    console.log('Bulb is OFF');
  }
}
class Switch {
  constructor() {
    this.command = null;
  }
 
  setCommand(command) {
    this.command = command;
  }
 
  executeCommand() {
    this.command.execute();
  }
}
const light = new LightBulb();
const On = new OnCommand(light);
const Off = new OffCommand(light);
 
const switchButton = new Switch();
 
switchButton.setCommand(On);
switchButton.executeCommand();
 
switchButton.setCommand(Off);
switchButton.executeCommand();


Output

Bulb is ON
Bulb is OFF


Components of Command Method

The components of the Command Method include

  • Command Interface: The Command interface declares the methods that should be implemented by all the concrete classes. It serves as a common template that declares the method that is common for all the classes.
  • Concrete Command class: The Concrete Command class implements the actions through the execute method and holds the information related to performed actions.
  • Receiver: The Receiver class contains the actual logic to process the requests.
  • Invoker: The invoker holds a reference to a command and triggers the execution of the command without knowing the specifics of the action being performed.

Diagrammatic Representation of Command Method:

Screenshot-(1212)

Below is the explanation of the above diagram:

In this diagram,

  • ON/OFF functionality of Light bulb using command design pattern, we can find `Command` class, which contains the methods that should be executed by all the remaining class which extends the `Command` class, here we declared the execute method that should be defined and implemented by the sub classes of `Command` class. i.e. `OnCommand` and `OffCommand` classes.
  • `execute` method contains the implementation for specific commands and calls the respective methods associated with those commands (`on` and `off`).
  • The implementation for `on` and `off` is mentioned in the `LightBulb` class which acts as the Reciever class.
  • `OnCommand` , `OffCommand` and `LightBulb` classes are directly associated. The `Switch` class acts as the invoker through which we can able to the set the specific command and execute that command and the defined methods `SetCommand` and `executeCommand` do this task.

Advantages of the Command Method in JavaScript Design Patterns

  • Decoupling: The Command method helps to decouple the sender of the request (client) and receiver of the request (Recievers) through Invoker. The client only knows how to send a request and the rest is abstracted. This gives a more generalized way to separate the tasks.
  • Flexibility and Extensibility: The Command method makes it easier to add new changes without modifying the underlying code promoting a flexible and extensible design.
  • Undo/Redo Functionality: The Command method stores the state of the command in the Concrete Command class which helps to restore the previous states easily.
  • Simplified Client Code: The client or the sender needs to know how to send a request without bothering about the underlying code. This makes the client code simplified.
  • Parameterization and Queuing: The Commands in the Command method can store specific parameters, allowing for parameterized actions. Commands can also be queued and executed in a specific order, providing control over the sequence of operations.

Disadvantages of the Command Method in JavaScript Design Patterns

  • Increased Complexity: For smaller and simple use cases, implementing the command method potentially makes the codebase look more complex and harder to manage.
  • Memory Overhead: For implementing Undo/Redo functionality, storing the previous state can lead to memory overhead, especially for use cases having more commands to execute.
  • Overhead of Creating Objects: Each command demands the creation of a new object which leads to Overhead of Objects in case of use cases having more number of commands.
  • Learning Curve: Understanding and implementing the Command Pattern might require developers to familiarize themselves with the concept, potentially resulting in a learning curve, especially for those new to design patterns.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads