Open In App

Command Method – Python Design Patterns

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Command Method is Behavioral Design Pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests and the queuing or logging of requests. Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door. It helps in promoting the “invocation of a method on an object” to full object status. Basically, it encapsulates all the information needed to perform an action or trigger an event.

Problem without using Command Method

Imagine you are working on a code editor. Your current task is to add the new buttons in the toolbar of the editor for various different operations. It’s definitely easy to create a single Button Class that can be used for the buttons. As we know that all the buttons used in the editor look similar, so what should we do? Should we create a lot of sub-classes for each place where the button is used?

Problem-without-Command-method

Problem-without-Command-method

Solution Using Command Method

Let’s have a look at the solution for the above-described problem. It’s always a good idea to divide the software into different layers which helps in easy coding as well as debugging. The command pattern suggests that objects shouldn’t send these requests directly. Instead, you should extract all of the request details, such as the object being called, the name of the method and the list of arguments into a separate command class with a single method that triggers this request.

Python3
"""Use built-in abc to implement Abstract classes and methods"""
from abc import ABC, abstractmethod

"""Class Dedicated to Command"""
class Command(ABC):
    
    """constructor method"""
    def __init__(self, receiver):
        self.receiver = receiver
    
    """process method"""
    def process(self):
        pass

"""Class dedicated to Command Implementation"""
class CommandImplementation(Command):
    
    """constructor method"""
    def __init__(self, receiver):
        self.receiver = receiver

    """process method"""
    def process(self):
        self.receiver.perform_action()

"""Class dedicated to Receiver"""
class Receiver:
    
    """perform-action method"""
    def perform_action(self):
        print('Action performed in receiver.')

"""Class dedicated to Invoker"""
class Invoker:
    
    """command method"""
    def command(self, cmd):
        self.cmd = cmd

    """execute method"""
    def execute(self):
        self.cmd.process()

"""main method"""
if __name__ == "__main__":
    
    """create Receiver object"""
    receiver = Receiver()
    cmd = CommandImplementation(receiver)
    invoker = Invoker()
    invoker.command(cmd)
    invoker.execute()

Output

Action performed in receiver.

Class Diagram

Following is the class diagram for the Command method

Class-diagram-Command-Method

Class-diagram-Command-Method

Advantages 

  • Open/Closed Principle: We can introduce the new commands into the application without breaking the existing client’s code.
  • Single Responsibility Principle: It’s really easy to decouple the classes here that invoke operations from other classes.
  • Implementable UNDO/REDO: It’s possible to implement the functionalities of UNDO/REDO with the help of Command method.
  • Encapsulation: It helps in encapsulating all the information needed to perform an action or an event.

Disadvantages

  • Complexity Increases: The complexity of the code increases as we are introducing certain layers between the senders and the receivers.
  • Quantity of classes increases: For each individual command, the quantity of the classes increases.
  • Concrete Command: Every individual command is a ConcreteCommand class that increases the volume of the classes for implementation and maintenance.

Applicability 

  • Implementing Reversible operations: As the Command method provides the functionalities for UNDO/REDO operations, we can possibly reverse the operations.
  • Parameterization: It’s always preferred to use Command method when we have to parameterize the objects with the operations.

Further Read – Command Method in Java
 



Previous Article
Next Article

Similar Reads

Difference Between Architectural Style, Architectural Patterns and Design Patterns
Many software professionals think that architectural styles and patterns are the same. Sadly, some of the software developers don’t understand the difference between architectural patterns and design patterns. In this article, we're going to summarize the differences between them. According to MSDN, architectural styles and patterns are the same th
7 min read
Connectivity and Composition Patterns | Design Patterns for Cloud Native Applications
In cloud-native applications, the architectural design becomes a critical aspect, defining the success of the entire solution. Connectivity and composition patterns are fundamental design principles that dictate how different components within a cloud-native application communicate and collaborate. Let's delve deeper into the significance of these
9 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 Why do the we use Command Method?Command Method e
6 min read
Command Pattern | C++ Design Patterns
The Command Pattern is a behavioral design pattern that focuses on encapsulating a request as an object, thereby decoupling the sender of the request from the receiver. This pattern allows you to parameterize objects with commands, delay or queue a request's execution, and support undoable operations. It's a fundamental pattern for implementing a w
7 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 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 make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
What is the Correlation Between System Design and Design Patterns?
System design and design patterns are closely related concepts in software engineering, with design patterns serving as reusable solutions to common design problems encountered during system design. System design and design patterns are interrelated concepts that work together to create robust and well-structured software systems. Important Topics
11 min read