Command Design pattern encapsulates the upcoming request into an object referred to as “Command”. This can help you capture each component of the request including the parameters inside the method and method too.
You will have all the information you might need such as a method, arguments, parameters, values, etc which you can use at a later point of time based on need. In this blog, we will highlight the need for a Command design pattern.
What is the Command Design Pattern?
Command Design Pattern is a behavioral design pattern in C++ object oriented programming which is used to contain all information about a request from the sender. It implements loose coupling and encapsulates all information required to set an action at a later point of time.
This information stored contains the information of the method such as the method and values for the parameters. Let us learn more about Command design patterns and when to use it in programming.
Command Design Pattern: Key Takeaways
- Command Design pattern captures the request and encapsulates it as an object which separates sender and receiver.
- You can easily create different commands with different parameters without having to change the invoker.
- You get more flexibility due to the loose coupling between sender and receiver.
- You can easily perform the undo and redo operations using command design patterns.
- Get log requests, undo/redo operations, easily pass, queue and more with command design pattern.
Why Use Command Design Pattern?
Nowadays we are frequently using reusable components in our web applications such as buttons, dropdowns, menus, checkbox, and more. These components can be used to build any web application and be used in any of them. For example, the checkbox can be used in any website with multiple options available.
This is where the command design pattern comes in place and frontend developers are unaware of the actions that will get triggered when a button is clicked. With command design patterns the person who clicks the button need not know about the command in action.
Any action can be used with the component easily based on the application requirement. For example, we can create separate classes for increment operation and decrement operation when a button is clicked.
Components of Command Design Pattern
There are some of the important command design patterns we need to perform the complete operation.
1. Command Interface
The Command interface is used to declare an interface where we execute an operation. It is used to define the execute () method for a particular problem statement. It ensures that every command has a clear indication of the actions they need to perform.
public interface Command {
void execute(); } |
2. Concrete Command Class
The Concrete Command class are specific actual commands that direct an action, event or trigger. It is used to define a binding between a receiver and action. It generally implements the execute() method using invoking operations such as receiver.
public class LightOnCommand implements Command {
private Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.turnOn(); } } |
Read More: What is Encapsulation in C++ Object Oriented Programming?
3. Receiver
The Receiver is a device which usually performs the actual operation based on the command received. It could be any specific action and it executes the task mentioned in the commands.
Receiver is any class which actually executes the tasks or actual work when command comes into action. When the command says “turn on” the light the device performs the function and turns on the light.
public class Light {
public void turnOn() { System.out.println(“Light is ON”); } } |
4. Invoker
The Invoker is a remote control responsible for starting the command execution during an operation. It does not know how the command and execution is taking place but holds the reference to the commands taking place in operation.
It stores the commands and may support features like commands queues or undo stacks.
public class RemoteControl {
private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } } |
Working of Command Design Pattern
The working of command design pattern is simple and it uses some core components such as invoker, concrete command, receiver, and command interface. They are responsible for executing the operations or tasks based on the clients requests.
The receiver first receives the command from the ConcreteCommand which tells how to perform operations related to the command. Now an interface comes with a execute() method with all details of what to implement. The concrete command helps the command interface and implement the execute() method. It also connects with the receiver to trigger the required action.
The invoker in the complete picture is responsible for executing the command given by the client based on the incoming request from the sender. The client is, however, responsible for creating the complete ConcreteCommand and also assigns the invoker and set the receiver.
- At the beginning you create the Receiver classes which can be any device such as light, speaker, stereo phones, etc
- Now the next step is to create a command interface which declares the execute() method and implement it by classes.
- Create the concrete command classes for all tasks which implement the command interface.
- Also, create the invoker class which is used to assign all commands to the methods for execution. It accepts the command as parameters.
- Create the client class i,e. RemoteApplication which will create the command object and assign them to the invoker class.
Read More: Lambda Expressions in C++ Programming
How to Use Command Design Pattern?
The Command Design pattern goes through a series of steps to become ready for action. Let us check some major steps while implementing the design pattern.
- You will need to define an interface or class which is used to define and declare the execute() method. This method will be used to carry out action in the process.
- Create different classes with different concrete commands with each class calling a method to the receiver and directing it to perform a specific action.
- The receiver class is a component which contains the complete actual logic which needs to be executed in the method. The command object will call the method to the receiver to direct them to perform actions.
- Create the invoker class which is used to trigger the command execute() method. It does not have any knowledge of what the operation contains. It simply calls the command.
- The client connects with the object through method calls and then it assigns the task to the invoker which will call the method when needed.
Examples of Command Design Pattern
Suppose there is a kitchen for which we need to design a smart kitchen automation system. The system will control different kitchen appliances such as toasters, coffee machines, microwaves, and more. Each device has its own unique function. Let us make this possible with the command design pattern.
- Appliances in kitchen can have different operations and interfaces
- The controller must execute actions without tight coupling each logic of the appliances.
- New devices can easily be added into the system without any major challenging changes.
These are some of the challenges we need to address while solving this problem statement. Read carefully as this will help you clear your concept in Command design pattern a bit more.
1. Command Interface
Here, we have created an execute() method which will direct different commands in the smart kitchen automation system.
// Command interface
public interface Command { void execute(); } |
2. Concrete Command Classes
We will now create different concrete command classes based on different kitchen devices we have available.
// Command to brew coffee
public class BrewCoffeeCommand implements Command { private CoffeeMachine coffeeMachine; public BrewCoffeeCommand(CoffeeMachine coffeeMachine) { this.coffeeMachine = coffeeMachine; } @Override public void execute() { coffeeMachine.brewCoffee(); } } // Command to toast bread public class ToastBreadCommand implements Command { private Toaster toaster; public ToastBreadCommand(Toaster toaster) { this.toaster = toaster; } @Override public void execute() { toaster.toast(); } } // Command to heat food public class HeatFoodCommand implements Command { private Microwave microwave; public HeatFoodCommand(Microwave microwave) { this.microwave = microwave; } @Override public void execute() { microwave.heat(); } } |
3. Receiver Class [Appliances]
This class is used to actually perform all tasks using different command interface classes.
// Coffee machine
public class CoffeeMachine { public void brewCoffee() { System.out.println(“Brewing coffee…”); } } // Toaster public class Toaster { public void toast() { System.out.println(“Toasting bread…”); } } // Microwave public class Microwave { public void heat() { System.out.println(“Heating food…”); } } |
4. Invoker (Kitchen Controller)
Invoker is the smart controller which sends the command signal to the receivers with the functions they need to perform. It does not have any information.
public class KitchenController {
private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } } |
5. Client (Main Code)
public class KitchenAutomationApp {
public static void main(String[] args) { // Receivers CoffeeMachine coffeeMachine = new CoffeeMachine(); Toaster toaster = new Toaster(); Microwave microwave = new Microwave(); // Commands Command brewCoffee = new BrewCoffeeCommand(coffeeMachine); Command toastBread = new ToastBreadCommand(toaster); Command heatFood = new HeatFoodCommand(microwave); // Invoker KitchenController controller = new KitchenController(); // Execute commands controller.setCommand(brewCoffee); controller.pressButton(); // Output: Brewing coffee… controller.setCommand(toastBread); controller.pressButton(); // Output: Toasting bread… controller.setCommand(heatFood); controller.pressButton(); // Output: Heating food… } } |
Also Read:
- Command Pattern | C++ Design Patterns
- Lambda Expressions in C++ (10 Deep Insights)
- Concept of OOP in C++: For Beginners In Programming
- What Are STL in C++
Learn C++ Programming with PW Skills
Strengthen your programming skills in C++ language with PW Skills Decode DSA With C++ Course made for beginners as well as professionals who want to level up their programming game. Master your logic making and solve a lot of real world problems within this course program.
This is a self paced program with pre-recorded lectures from our dedicated mentors which will help you prepare a strong job portfolio, build job networks, soft skills and prepare you for a solid foundation for a career in programming and development. Complete the course and make yourself job ready only at pwskills.com
Command Design Pattern In C++ FAQs
Q1. What is the Command Design pattern?
Ans: Command Design Pattern is a behavioral design pattern in C++ object oriented programming which is used to contain all information about a request from the sender. It implements loose coupling and encapsulates all information required to set an action at a later point of time.
Q2. What are the major components of the Command design pattern? Ans: Command Interface, Concrete Command classes, receiver classes, invoker, and client are some of the major components of Command design pattern.
Ans: Command Interface, Concrete Command classes, receiver classes, invoker, and client are some of the major components of Command design pattern.
Q3. What is the command pattern in functional programming?
Ans: Command pattern is a behavioural design pattern which is used to enclose a request into an object with all major information encapsulated inside. This helps in implementing various operations such as method arguments, delay, queue or undo, redo operations, and more.
Q4. What is Invoker in Command design pattern?
Ans: The Invoker is a remote control responsible for starting the command execution during an operation. It does not know how the command and execution is taking place but holds the reference to the commands taking place in operation.
Q5. What is the use of Receiver in Command design pattern?
Ans: The receiver is the actual component which knows how to perform the actual operation based on the command passed. It can be any device which initiates and perform the task.