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