- Python Design Patterns - Home
- Python Design Patterns - Introduction
- Python Design Patterns - Gist
- Model View Controller Pattern
- Python Design Patterns - Singleton
- Python Design Patterns - Factory
- Python Design Patterns - Builder
- Python Design Patterns - Prototype
- Python Design Patterns - Facade
- Python Design Patterns - Command
- Python Design Patterns - Adapter
- Python Design Patterns - Decorator
- Python Design Patterns - Proxy
- Chain of Responsibility Pattern
- Python Design Patterns - Observer
- Python Design Patterns - State
- Python Design Patterns - Strategy
- Python Design Patterns - Template
- Python Design Patterns - Flyweight
- Python Design Patterns - Abstract Factory
- Python Design Patterns - Object Oriented
- Object Oriented Concepts Implementation
- Python Design Patterns - Iterator
- Python Design Patterns - Dictionaries
- Python Design Patterns - Lists Data Structure
- Python Design Patterns - Sets
- Python Design Patterns - Queues
- Python Design Patterns - Strings & Serialization
- Python Design Patterns - Concurrency
- Python Design Patterns - Anti Pattern
- Python Design Patterns - Exception Handling
Python Design Patterns Resources
Python Design Patterns - Command Pattern
Command Pattern adds a level of abstraction between actions and includes an object, which invokes these actions.
In this design pattern, client creates a command object that includes a list of commands to be executed. The command object created implements a specific interface.
Following is the basic architecture of the command pattern −
Example - How to implement the command pattern?
We will now see how to implement the design pattern.
main.py
from abc import ABC, abstractmethod
class Command(ABC):
def __init__(self, receiver):
self.receiver = receiver
def process(self):
pass
class Implementator(Command):
def __init__(self, receiver):
self.receiver = receiver
def process(self):
self.receiver.perform_action()
class Receiver:
def perform_action(self):
print('Receiver performed an action.')
class Invoker:
def command(self, cmd):
self.cmd = cmd
def execute(self):
self.cmd.process()
if __name__ == "__main__":
receiver = Receiver()
cmd = Implementator(receiver)
invoker = Invoker()
invoker.command(cmd)
invoker.execute()
Output
The above program generates the following output −
Receiver performed an action.
Explanation
The output showcases all the necessary components of command design pattern.
Advertisements