Command Method | JavaScript Design Patterns
Last Updated :
31 Oct, 2023
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.
Important Topics for the Command Method in JavaScript Design Patterns
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();
OutputBulb 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:
.png)
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.
Become a System Design expert and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.
Step into the Three 90 Challenge – 90 days to push limits, break barriers, and become the best version of yourself! Don't miss your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!
Similar Reads
JavaScript Design Patterns Tutorial
Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
8 min read
Creational Software Design Patterns in JavaScript
Builder Method | JavaScript Design Pattern
The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
9 min read
Prototype Method - JavaScript Design Pattern
A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
3 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
6 min read
Behavioural Software Design Patterns in JavaScript
Template Method | JavaScript Design Patterns
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
10 min read
State Method Design Patterns in JavaScript
State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
4 min read
Iterator Method | JavaScript Design Pattern
Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
4 min read
Strategy Method | JavaScript Design Pattern
Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
8 min read
Observer Method – JavaScript Design Pattern
Observer design pattern, a staple of behavioral design patterns in JavaScript, provides a means to establish a one-to-many relationship between objects. This design pattern is especially valuable for decoupling components and facilitating extensibility in software applications. By employing this pat
10 min read
Command Method | JavaScript Design Patterns
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. Important Topics for the Command Method in JavaScript Design Patterns
6 min read
Visitor Pattern | JavaScript Design Patterns
The visitor pattern is a behavioral design pattern that allows you to add new behaviors or operations to a set of objects without modifying their structure. It achieves this by separating the algorithm from the objects on which it operates. Important Topics for the Visitor Pattern in JavaScript Desi
12 min read
Structural Software Design Patterns in JavaScript
Adapter Method | JavaScript Design Patterns
Adapter Pattern in JavaScript is a structural design pattern that allows you to make one interface or object work with another that has a different interface. It acts as a bridge, enabling the compatibility of two systems that would not naturally work together. Important Topics for the Adapter Metho
8 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation
4 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to ma
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emer
9 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise fro
5 min read
Factory Method in JavaScript | Design Pattern
The Factory Design Pattern is a creational pattern that allows for the creation of objects without exposing the creation logic to the client. It involves creating a separate factory function that is responsible for creating instances of various related objects based on a specified input. In modern s
7 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Fl
4 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite hel
6 min read
Software Design Pattern in other Programming Languages
Python Design Patterns Tutorial
Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
8 min read
Modern C++ Design Patterns Tutorial
Design patterns in C++ help developers create maintainable, flexible, and understandable code. They encapsulate the expertise and experience of seasoned software architects and developers, making it easier for newer programmers to follow established best practices. What are C++ Design Patterns?A des
7 min read