Created
May 3, 2024 13:30
-
-
Save grafuls/580e5cafc411e76d956625893ed57e7d to your computer and use it in GitHub Desktop.
Command Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import partial | |
class CommandException(Exception): | |
def __init__(self, message): | |
self.message = message | |
class Command: | |
""" | |
The Command class encapsulates an action (a function or method) and its arguments. | |
It allows the action to be executed later with the execute method. | |
""" | |
def __init__(self, func, *args, **kwargs): | |
""" | |
Initializes a new instance of the Command class. | |
:param func: The function or method to be executed. | |
:param args: The positional arguments for the function. | |
:param kwargs: The keyword arguments for the function. | |
""" | |
self.func = partial(func, *args, **kwargs) | |
def execute(self): | |
""" | |
Executes the encapsulated function or method. | |
If an exception occurs during execution, it is caught and printed. | |
""" | |
try: | |
self.func() | |
except Exception as e: | |
raise CommandException(e) | |
class Invoker: | |
""" | |
The Invoker class maintains a list of Command instances. | |
It allows all commands to be executed in the order they were added with the execute_commands method. | |
""" | |
def __init__(self): | |
""" | |
Initializes a new instance of the Invoker class. | |
""" | |
self.commands: list[Command] = [] | |
def add_command(self, command: Command): | |
""" | |
Adds a Command instance to the list of commands. | |
:param command: The Command instance to be added. | |
""" | |
self.commands.append(command) | |
def execute_commands(self): | |
""" | |
Executes all Command instances in the list in the order they were added. | |
""" | |
for command in self.commands: | |
try: | |
command.execute() | |
except CommandException: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment