Have you heard about Command pattern in C++ language? When you do not want the senders and receivers to be separate we use command pattern in C++ programming a part of C++ language object oriented programming.
The objects kept encapsulated can be stored, reused, and passed around for execution at a later point of time offering flexibility and efficiency in the system. In this blog, we will learn more about command pattern and their uses in detail.
What is Command Pattern In C++?
As per the definition, Command Pattern is a behavioral design pattern in C++ object oriented programming which is used to contain or encapsulate all major information which is used to perform and action or trigger some events at a later instant of time.
We might need these patterns in C++ programming due to various different reasons such as when we need to perform a set of operations at a later scheduled time or when we want to support undo and redo. There is more to the use of Command patterns in C++ programming, let us learn ahead in this blog.
What is the Use of Command Pattern In C++?
Command pattern is used to encapsulate information from sender to receiver acting as a barrier storing information and data. It can be used when we need to parameterize clients with different requests, queues or log requests.
The command pattern method does not call the method directly it instead wraps the request in a command object and then executes them. Command, Concretecommand, receiver, invoker, client are some of the components of Command pattern in C++ language. We can use these command patterns during the following given conditions.
- Command patterns can decouple objects that invoke operations from those that perform them.
- When you want to get access to undo, redo, or log information.
- When you want to parameterize objects with operations.
- When you need to queue operations or perform them at a later time.
When a sender makes a request it is encapsulated as an object and decouples the sender of the request from the receiver. It helps in completing undoable operations.
Read More: What is Encapsulation in OOPs? Explanation
Key Components of Command Pattern In C++ Programming
Let us look at some major components of the Command pattern in C++ programming language.
1. Command Interface/Abstract Class
This is an abstract class which is used to declare the interface of all commands which is typically an execute() method. It is used to implement undo() or redo() methods.
It ensures that all commands follow a common general structure which enables the invokers to trigger any command without knowing the functional details.
2. ConcreteCommand
The ConcreteCommand which is used for specific implementation of the command interface. It is used to bind a receiver with a specific action.
It calls the appropriate action on the receiver when its execute () method is called in the method. It also stores the state needed to perform and possibly undo the command.
3. Receiver
The Receiver is the object which is used to perform a specific action during execution of a command. It is familiar with how to perform the requested action in the system.
It contains all business logic which is triggered by the ConcreteCommand during the method calls. For example, in the smart automation system at home the intelligence system is aware of how to turn on and turn off the lights. It can also be used in file systems, document editors and more.
Read More: What is STL In C++? Explain Completely
4. Invoker
The invoker is a component in the command pattern used to create concreteCommand objects and assign them to the invoker. It is used to configure the entire command pattern by deciding which command can be used with which receiver and then passes it to the invoker.
It acts as a bridge between the sender and receiver while ensuring that both these entities remain decoupled from the receiver. For example, the remote control, button or menu item can be considered as an invoker in the system.
5. Client
The client in the Command pattern components is a code which is used to create ConcreteCommand objects and assign them to the invoker. It configures the command pattern by deciding which command to use with which receiver and then passes it to the invoker.
For example, the main() function is an initialization code in the application.
Working of Command Patterns In C++ Programming Language
The four major components are responsible for the complete workflow of the command pattern in C++ programming.
- Command
- Receiver
- Invoker
- Client
The command object has complete information about the receiver and is responsible for invoking a method of the receiver in the process. The receiver object executes these methods by aggregation and when the execute () method is called.
An Invoker is present which executes a command and monitors the logs of the command execution. The invoker itself does not know anything about the concrete command. The client decides which receiver objects are held using the client object and also decides which receiver to assign the command objects and which one the invoker.
Examples of Command Pattern in C++ Programming
Let us try to understand the command pattern using a simple problem statement.
Problem Statement 1
Take a remote control where the remote control is an invoker and buttons are the command. Tv or Light is the receiver in the system and the user is the client. Let us create a command pattern using the C++ programming language for this statement.
#include <iostream>
#include <memory> #include <vector> using namespace std; // Receiver class Light { public: void turnOn() { cout << “Light is ON\n”; } void turnOff() { cout << “Light is OFF\n”; } }; // Command Interface (Abstract Class) class Command { public: virtual void execute() = 0; virtual ~Command() {} }; // Concrete Command to turn ON the light class TurnOnCommand : public Command { Light& light; public: TurnOnCommand(Light& l) : light(l) {} void execute() override { light.turnOn(); } }; // Concrete Command to turn OFF the light class TurnOffCommand : public Command { Light& light; public: TurnOffCommand(Light& l) : light(l) {} void execute() override { light.turnOff(); } }; // Invoker class RemoteControl { Command* command; public: void setCommand(Command* cmd) { command = cmd; } void pressButton() { if (command) { command->execute(); } } }; // Client int main() { Light livingRoomLight; TurnOnCommand turnOn(livingRoomLight); TurnOffCommand turnOff(livingRoomLight); RemoteControl remote; remote.setCommand(&turnOn); remote.pressButton(); // Output: Light is ON remote.setCommand(&turnOff); remote.pressButton(); // Output: Light is OFF return 0; } |
Output
![]() |
In the above code you will bind each component function together where the receiver is the actual object that knows how to perform the operation with exact conditional statements. The command interface is the abstract class with concrete command logics.
The invoker then chooses how to execute the commands and the client ties it all together to complete the entire system and perform the operation.
Problem Statement 2
We are designing a system that uses the command design pattern to decouple the invoke from the receiver. The objective is to show that the system can perform undoable solutions like Undo, Redo, macros and more.
#include <iostream>
#include <string> // Receiver class TextEditor { private: std::string text; public: void addText(const std::string& newText) { text += newText; std::cout << “Text after adding: ” << text << std::endl; } void removeText(int count) { if (count > text.size()) count = text.size(); text.erase(text.size() – count); std::cout << “Text after removing: ” << text << std::endl; } const std::string& getText() const { return text; } }; // Command interface class Command { public: virtual void execute() = 0; virtual ~Command() {} }; // Concrete Command: Add Text class AddTextCommand : public Command { private: TextEditor& editor; std::string newText; public: AddTextCommand(TextEditor& editor, const std::string& text) : editor(editor), newText(text) {} void execute() override { editor.addText(newText); } }; // Concrete Command: Remove Text class RemoveTextCommand : public Command { private: TextEditor& editor; int count; public: RemoveTextCommand(TextEditor& editor, int count) : editor(editor), count(count) {} void execute() override { editor.removeText(count); } }; // Invoker class EditorInvoker { private: Command* command; public: void setCommand(Command* cmd) { command = cmd; } void clickButton() { if (command) command->execute(); } }; // Main function demonstrating the pattern int main() { TextEditor editor; // Create command objects AddTextCommand addHello(editor, “Hello “); AddTextCommand addWorld(editor, “World!”); RemoveTextCommand removeLast6(editor, 6); // Create the invoker EditorInvoker button; // Simulate button clicks button.setCommand(&addHello); button.clickButton(); // Output: Text after adding: Hello button.setCommand(&addWorld); button.clickButton(); // Output: Text after adding: Hello World! button.setCommand(&removeLast6); button.clickButton(); // Output: Text after removing: Hello return 0; } |
Output
![]() |
In the adobe code, we have to button one is to “add text” and other is to “remove characters” from the text. We are encapsulating these actions into command objects to perform these actions using buttons.
We are using the receiver to define the logic for text operations. With the command interface we define the execute () method. The invoker acts as a button press handler which holds a command and executes it via a method i,e. clickButton(). The main() function consists of the client code.
- The main function creates a command
- It then sets the command in invoker and the invoker calls the command.execute() method
- The command calls the receiver with the logic or text editor method.
- The receiver then performs the real work and executes the process with text addition and character removal.
Advantages of using Command Pattern In C++ Language
The Command pattern offers various benefits on design and language specific levels which also help to implement flexible, decoupled, and extensible architecture. Check some of the major advantages below.
1. Decoupling Sender and Receiver
The Command pattern makes sure that the sender of the request is decoupled from the receiver. This refrains the sender from knowing or handling how a request is handled.
The invoker does not need to stay informed on the workflow of commands and this low coupling between classes makes code more easy to maintain and modify.
2. Encapsulation of Requests
The command interface encapsulates a request from the sender as an object which decouples it from the receiver’s end. This is useful especially for UI Interactions, game command systems, job scheduling systems, and more.
3. Queuing Commands
The commands in this pattern can easily be queued and allow implementation of undo and redo functions easily. This is useful for applications where the complete order of execution is important.
You can easily store a history of commands and call the undo() methods wherever you want. It is useful for editors, games, or command line interfaces.
4. Easy to add New Commands
With the Command pattern it is easy to add a new operation where you just have to create a new ConcreteCommand class and it is done.
There is no need to change existing code in the receiver or invoker in the system. This is really helpful with extensible applications such as plugins or other tools. You can easily add new command classes inside without having to alter the existing ones.
5. Logging and Auditing
You can easily track the system and perform easy debugging with effecting log and audit in the commands. As each command is encapsulated as an object in C++ language you can easily log or audit the command as per need.
6. Promotes Usability And Flexibility
Commands in this system are often small and isolated objects which can easily be tested independently using unit test methods. It is easier to mock receivers or isolate all logics for debugging. With decoupling of sender and receivers flexibility also increases.
Disadvantages of using Command Pattern In C++
While the Command pattern holds many advantages, it also suffers from some limitations mentioned below.
1. Increased Code Complexity
As you will need to create a separate command class for each method or action this will result in many classes and files which can even overload the system and make it more complex. The more the number of actions required the more classes you will need.
2. Duplicate Boilerplate Code
As the structure is similar most of the time for storing and calling a receiver method. This leads to duplicate boilerplate code across the command classes . This might need extra memory management to handle it using smart pointers.
3. More memory usages
With more object enclosing commands can lead to increased memory overhead in the system. It might take place especially when you are dealing with a large number of commands.
4. Complex Learning Curve
When we encapsulate requests into objects it might lead to performance overhead while using commands for specific functions. This might become a matter of concern in applications with critical performance responsibilities. As we are creating and storing many small objects and managing their queue can be a reason for the performance overhead.
5. Harder Debugging Flow
It becomes harder to trace methods call flow and even difficult to inspect real time changes due to execution logic encapsulation in command objects. It makes debugging even harder than the normal scenarios. It might become an issue or a bottleneck in the process.
Also Read:
- Lambda Expressions in C++ (10 Deep Insights)
- Concept of OOP in C++: For Beginners In Programming
- CPP Type & C++ Data Types: For Beginners
- 9 Powerful Ways C++ Multithreading Can Build Faster and Smarter Applications
- Learn C++ Programming with Data Structures
Beat your best timing in C++ programming with PW Skills Decode DSA With C++ Course suitable for beginners as well as professionals who want to level up their programming game. Strengthen your logic making and solve plenty 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 Pattern in C++ FAQs
Q1. What is Command Pattern in C++ Programming?
Ans: Command pattern is used to encapsulate information from sender to receiver acting as a barrier storing information and data. It can be used when we need to parameterize clients with different requests, queues or log requests.
Q2. What are the components in the Command pattern?
Ans: Command interface, ConcreteCommand, Receiver, Invoker, Client are some of the components used in the command pattern in C++ programming language.
Q3. What are the four main types of command pattern?
Ans: The four main types of command pattern used in various fields are structural, behavioral, and creational design patterns. These patterns are used across various fields such as software engineering, clothing design, art, and more.
Q4. What is the command pattern in functional programming?
Ans: In Functional programming command is a behavioral design pattern which turns a request into object that contains all information and data connected to the requests pushed by the sender.