Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Command Design Pattern
Next article icon

Command Design Pattern

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Command Design Pattern is a behavioral design pattern that turns a request into a stand-alone object called a command. With the help of this pattern, you can capture each component of a request, including the object that owns the method, the parameters for the method, and the method itself. By doing this, you can easily pass, queue, or log requests and support operations like undo/redo.

command-design-pattern-new-

Table of Content

  • What is the Command Design Pattern?
  • Components of the Command Design Pattern
  • How to implement Command Design Pattern?
  • Command Design Pattern example
  • When to use the Command Design Pattern 
  • When not to use the Command Design Pattern

What is the Command Design Pattern?

The Command Design Pattern is a behavioral design pattern that turns a request into a stand-alone object called a command. With the help of this pattern, you can capture each component of a request, including the object that owns the method, the parameters for the method, and the method itself.

  • The Command Pattern encapsulates a request as an object, allowing for the separation of sender and receiver.
  • Commands can be parameterized, meaning you can create different commands with different parameters without changing the invoker.
  • It decouples the sender from the receiver, providing flexibility and extensibility.
  • The pattern supports undoable operations by storing the state or reverse commands.

Components of the Command Design Pattern

1. Command Interface

The Command Interface is like a rulebook that all command classes follow. It declares a common method, execute(), ensuring that every concrete command knows how to perform its specific action. It sets the standard for all commands, making it easier for the remote control to manage and execute diverse operations.

2. Concrete Command Classes

Concrete Command Classes are the specific commands, like turning on a TV or adjusting the stereo volume. Each class encapsulates the details of a particular action. These classes act as executable instructions that the remote control can trigger without worrying about the small details.

3. Invoker (Remote Control)

The Invoker, often a remote control, is the one responsible for initiating command execution. It holds a reference to a command but doesn't delve into the specifics of how each command works. It's like a button that, when pressed, makes things happen.

4. Receiver (Devices)

The Receiver is the device that knows how to perform the actual operation associated with a command. It could be a TV, stereo, or any other device. Receivers understand the specific tasks mentioned in commands.

  • If a command says, "turn on," the Receiver (device) knows precisely how to execute that action.
  • The Receiver-Command relationship separates responsibilities, making it easy to add new devices or commands without messing with existing functionality.

How to implement Command Design Pattern?

Below are the simple steps to implement the Command Design Pattern:

  1. Create the Command Interface: Define an interface or abstract class that declares the execute() method. This method will be called to carry out the action.
  2. Create Concrete Command Classes: Implement the command interface in multiple classes. Each class will represent a different command and will call the appropriate method on the receiver to perform the specific action.
  3. Define the Receiver Class: This class contains the actual logic that needs to be executed. The command objects will call methods on this receiver to perform actions.
  4. Create the Invoker Class: The invoker triggers the command’s execute() method but doesn’t know the details of the operation. It simply knows that it needs to call the command.
  5. Client Uses the Command: The client creates the concrete command objects and associates them with the receiver. It then assigns commands to the invoker, which will call them when needed.

Command Design Pattern example

Problem Statement:

Imagine you are tasked with designing a remote control system for various electronic devices in a smart home. The devices include a TV, a stereo, and potentially other appliances. The goal is to create a flexible remote control that can handle different types of commands for each device, such as turning devices on/off, adjusting settings, or changing channels.

What can be the challenges while implementing this system?

  • Devices can have different functionalities, so designing a remote control that can easily handle different device types with varying functionalities without becoming highly complex.
  • Implementing a remote control that supports various commands without tightly coupling ensuring the remote control can execute commands for different devices without needing extensive modifications for each new command.
  • Designing a system that allows users to customize the behavior of the remote control dynamically.

How Command Pattern help to solve above challenges?

The Command Pattern can be employed to address these challenges. It introduces a level of abstraction between the sender of a command (remote control) and the receiver of the command (electronic devices).

  • The Command Pattern decouples the sender (Invoker) from the receiver (Devices).
  • The remote control doesn't need to know the specific details of how each device operates; it only triggers commands.
  • New devices or commands can be added without modifying existing code.
  • The remote control can work with any device that implements the common command interface.

CommandPatternExampledrawio-(3)

Below is the code of above problem statement using Command Pattern:

1. Command Interface

The Command interface declares a method, often named execute(). This method is meant to encapsulate a specific operation. The interface sets a contract for concrete command classes, defining the execute() method that encapsulates the operation to be performed.

Java
// Command interface public interface Command {     void execute(); } 

2. Concrete Command Classes

Concrete command classes implement the Command interface. Each class encapsulates a specific operation related to devices. Each concrete command class provides a specific implementation of the execute() method, defining how a particular device operation (turning on, turning off, adjusting volume, changing channel) is executed.

Java
// Concrete command for turning a device on public class TurnOnCommand implements Command {     private Device device;      public TurnOnCommand(Device device) {         this.device = device;     }      @Override     public void execute() {         device.turnOn();     } }  // Concrete command for turning a device off public class TurnOffCommand implements Command {     private Device device;      public TurnOffCommand(Device device) {         this.device = device;     }      @Override     public void execute() {         device.turnOff();     } }  // Concrete command for adjusting the volume of a stereo public class AdjustVolumeCommand implements Command {     private Stereo stereo;      public AdjustVolumeCommand(Stereo stereo) {         this.stereo = stereo;     }      @Override     public void execute() {         stereo.adjustVolume();     } }  // Concrete command for changing the channel of a TV public class ChangeChannelCommand implements Command {     private TV tv;      public ChangeChannelCommand(TV tv) {         this.tv = tv;     }      @Override     public void execute() {         tv.changeChannel();     } } 

3. Receiver Classes (Devices)

The Device interface declares methods related to device functionality, such as turnOn() and turnOff(). This interface sets a contract for device classes, defining common operations that concrete devices should support.

Java
// Receiver interface public interface Device {     void turnOn();     void turnOff(); }  // Concrete receiver for a TV public class TV implements Device {     @Override     public void turnOn() {         System.out.println("TV is now on");     }      @Override     public void turnOff() {         System.out.println("TV is now off");     }      public void changeChannel() {         System.out.println("Channel changed");     } }  // Concrete receiver for a stereo public class Stereo implements Device {     @Override     public void turnOn() {         System.out.println("Stereo is now on");     }      @Override     public void turnOff() {         System.out.println("Stereo is now off");     }      public void adjustVolume() {         System.out.println("Volume adjusted");     } } 

4. Invoker Class (Remote Control):

The invoker class holds a reference to a Command object and triggers its execution through the execute() method. The invoker doesn't know the specific details of the command or the devices. It simply calls the execute() method on the current command, allowing for flexible and dynamic control over different devices.

Java
// Invoker public class RemoteControl {     private Command command;      public void setCommand(Command command) {         this.command = command;     }      public void pressButton() {         command.execute();     } } 

Complete code for the above example

Below is the complete code for the above example:

Java
// Command interface interface Command {     void execute(); }  // Concrete command for turning a device on class TurnOnCommand implements Command {     private Device device;      public TurnOnCommand(Device device) {         this.device = device;     }      @Override     public void execute() {         device.turnOn();     } }  // Concrete command for turning a device off class TurnOffCommand implements Command {     private Device device;      public TurnOffCommand(Device device) {         this.device = device;     }      @Override     public void execute() {         device.turnOff();     } }  // Concrete command for adjusting the volume of a stereo class AdjustVolumeCommand implements Command {     private Stereo stereo;      public AdjustVolumeCommand(Stereo stereo) {         this.stereo = stereo;     }      @Override     public void execute() {         stereo.adjustVolume();     } }  // Concrete command for changing the channel of a TV class ChangeChannelCommand implements Command {     private TV tv;      public ChangeChannelCommand(TV tv) {         this.tv = tv;     }      @Override     public void execute() {         tv.changeChannel();     } }  // Receiver interface interface Device {     void turnOn();     void turnOff(); }  // Concrete receiver for a TV class TV implements Device {     @Override     public void turnOn() {         System.out.println("TV is now on");     }      @Override     public void turnOff() {         System.out.println("TV is now off");     }      public void changeChannel() {         System.out.println("Channel changed");     } }  // Concrete receiver for a stereo class Stereo implements Device {     @Override     public void turnOn() {         System.out.println("Stereo is now on");     }      @Override     public void turnOff() {         System.out.println("Stereo is now off");     }      public void adjustVolume() {         System.out.println("Volume adjusted");     } }  // Invoker class RemoteControl {     private Command command;      public void setCommand(Command command) {         this.command = command;     }      public void pressButton() {         command.execute();     } }  // Example usage public class CommandPatternExample {     public static void main(String[] args) {         // Create devices         TV tv = new TV();         Stereo stereo = new Stereo();          // Create command objects         Command turnOnTVCommand = new TurnOnCommand(tv);         Command turnOffTVCommand = new TurnOffCommand(tv);         Command adjustVolumeStereoCommand = new AdjustVolumeCommand(stereo);         Command changeChannelTVCommand = new ChangeChannelCommand(tv);          // Create remote control         RemoteControl remote = new RemoteControl();          // Set and execute commands         remote.setCommand(turnOnTVCommand);         remote.pressButton(); // Outputs: TV is now on          remote.setCommand(adjustVolumeStereoCommand);         remote.pressButton(); // Outputs: Volume adjusted          remote.setCommand(changeChannelTVCommand);         remote.pressButton(); // Outputs: Channel changed          remote.setCommand(turnOffTVCommand);         remote.pressButton(); // Outputs: TV is now off     } } 
Output
TV is now on Volume adjusted Channel changed TV is now off 

When to use the Command Design Pattern 

  • Decoupling is Needed:
    • In order to separate the requester making the request (the sender) from the object executing it, use the Command Pattern.
    • Your code will become more expandable and adaptable as a result.
  • Undo/Redo Functionality is Required:
    • If you need to support undo and redo operations in your application, the Command Pattern is a good fit.
    • Each command can encapsulate an operation and its inverse, making it easy to undo or redo actions.
  • Support for Queues and Logging:
    • If you want to maintain a history of commands, log them, or even put them in a queue for execution, the Command Pattern provides a structured way to achieve this.
  • Dynamic Configuration:
    • When you need the ability to dynamically configure and assemble commands at runtime, the Command Pattern allows for flexible composition of commands.

When not to use the Command Design Pattern

  • Simple Operations:
    • For very simple operations or one-off tasks, introducing the Command Pattern might be overkill.
    • It's beneficial when you expect your operations to become more complex or when you need to support undo/redo.
  • Tight Coupling is Acceptable:
    • If the sender and receiver of a request are tightly coupled and changes in one do not affect the other, using the Command Pattern might introduce unnecessary complexity.
  • Overhead is a Concern:
    • In scenarios where performance and low overhead are critical factors, introducing the Command Pattern might add some level of indirection and, in turn, impact performance.
  • Limited Use of Undo/Redo:
    • If your application does not require undo/redo functionality and you do not anticipate needing to support such features in the future, the Command Pattern might be unnecessary complexity.



Next Article
Command Design Pattern

K

kartik
Improve
Article Tags :
  • Design Pattern
  • System Design

Similar Reads

    Software Design Patterns Tutorial
    Software design patterns are important tools developers, providing proven solutions to common problems encountered during software development. This article will act as tutorial to help you understand the concept of design patterns. Developers can create more robust, maintainable, and scalable softw
    9 min read
    Complete Guide to Design Patterns
    Design patterns help in addressing the recurring issues in software design and provide a shared vocabulary for developers to communicate and collaborate effectively. They have been documented and refined over time by experienced developers and software architects. Important Topics for Guide to Desig
    11 min read
    Types of Software Design Patterns
    Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way th
    9 min read

    1. Creational Design Patterns

    Creational Design Patterns
    Creational Design Patterns focus on the process of object creation or problems related to object creation. They help in making a system independent of how its objects are created, composed, and represented. Creational patterns give a lot of flexibility in what gets created, who creates it, and how i
    4 min read

    Types of Creational Patterns

    Factory method Design Pattern
    The Factory Method Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created. This pattern is particularly useful when the exact types of objects to be created may vary or need
    7 min read
    Abstract Factory Pattern
    The Abstract Factory Pattern is one of the creational design patterns that provides an interface for creating families of related or dependent objects without specifying their concrete classes and implementation, in simpler terms the Abstract Factory Pattern is a way of organizing how you create gro
    8 min read
    Singleton Method Design Pattern in JavaScript
    Singleton Method or Singleton Design Pattern is a part of the Gang of Four design pattern and it is categorized under creational design patterns. It is one of the most simple design patterns in terms of modeling but on the other hand, this is one of the most controversial patterns in terms of comple
    9 min read
    Singleton Method Design Pattern
    The Singleton Method Design Pattern ensures a class has only one instance and provides a global access point to it. It’s ideal for scenarios requiring centralized control, like managing database connections or configuration settings. This article explores its principles, benefits, drawbacks, and bes
    11 min read
    Prototype Design Pattern
    The Prototype Design Pattern is a creational pattern that enables the creation of new objects by copying an existing object. Prototype allows us to hide the complexity of making new instances from the client. The existing object acts as a prototype and contains the state of the object. Table of Cont
    8 min read
    Builder Design Pattern
    The Builder Design Pattern is a creational pattern used in software design to construct a complex object step by step. It allows the construction of a product in a step-by-step manner, where the construction process can change based on the type of product being built. This pattern separates the cons
    9 min read

    2. Structural Design Patterns

    Structural Design Patterns
    Structural Design Patterns are solutions in software design that focus on how classes and objects are organized to form larger, functional structures. These patterns help developers simplify relationships between objects, making code more efficient, flexible, and easy to maintain. By using structura
    7 min read

    Types of Structural Patterns

    Adapter Design Pattern
    One structural design pattern that enables the usage of an existing class's interface as an additional interface is the adapter design pattern. To make two incompatible interfaces function together, it serves as a bridge. This pattern involves a single class, the adapter, responsible for joining fun
    8 min read
    Bridge Design Pattern
    The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. There are 2 parts in Bridge design pattern : AbstractionImplementationThis is a design mechanism that encapsulates an implementation class inside of an interface class. The br
    4 min read
    Composite Method | Software Design Pattern
    Composite Pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. The main idea behind the Composite Pattern is to build a tree structure of objects, where individual objects and composite objects share a common interface. T
    9 min read
    Decorator Design Pattern
    The Decorator Design Pattern is a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components.Important Top
    9 min read
    Facade Method Design Pattern
    Facade Method Design Pattern is a part of the Gang of Four design patterns and it is categorized under Structural design patterns. Before we go into the details, visualize a structure. The house is the facade, it is visible to the outside world, but beneath it is a working system of pipes, cables, a
    8 min read
    Flyweight Design Pattern
    The Flyweight design pattern is a structural pattern that optimizes memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, which is particularly useful when dealing with a large number of similar objects.Flywei
    10 min read
    Proxy Design Pattern
    The Proxy Design Pattern a structural design pattern is a way to use a placeholder object to control access to another object. Instead of interacting directly with the main object, the client talks to the proxy, which then manages the interaction. This is useful for things like controlling access, d
    9 min read

    3. Behvioural Design Patterns

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences