Wrapping Actions for Flexible Execution
In essence, the Command Design Pattern simplifies your code by wrapping actions in separate objects, offering a flexible and controlled way to trigger and execute functionalities within your software.
class Command:
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
raise NotImplementedError("Subclasses must implement this method")
class ConcreteCommand1(Command):
def execute(self):
self.receiver.action1()
class ConcreteCommand2(Command):
def execute(self):
self.receiver.action2()
class Receiver:
def action1(self):
print("Receiver action 1 executed")
def action2(self):
print("Receiver action 2 executed")
# Create a invoker and receiver
invoker = Invoker()
receiver = Receiver()
# Create concrete commands and add them to the invoker
invoker.add_command(ConcreteCommand1(receiver))
invoker.add_command(ConcreteCommand2(receiver))
# Execute commands
invoker.execute_commands()