Skip to content
Build From Zero

How to implement command design pattern in python?

Tutorial, Python, Pattern1 min read

Potions Class

src/interface.py
1import abc
2
3
4class CalcCmdAbs(metaclass=abc.ABCMeta):
5 def __init__(self, *args, **kwargs):
6 self._args = args
7 self._kwargs = kwargs
8
9 @property
10 @abc.abstractmethod
11 def name(self):
12 raise NotImplemented()
13
14 def execute(self):
15 raise NotImplemented()
src/commands.py
1from .interface import CalcCmdAbs
2
3OPERATORS = list()
4
5
6def register_operator(cls):
7 OPERATORS.append(cls)
8 return cls
9
10
11@register_operator
12class AddCmd(CalcCmdAbs):
13 name = "add"
14
15 def __init__(self, a, b):
16 super().__init__(a, b)
17 self.a = a
18 self.b = b
19
20 def execute(self):
21 return self.a + self.b
22
23
24@register_operator
25class SubtractCmd(CalcCmdAbs):
26 name = "subtract"
27
28 def __init__(self, a, b):
29 super().__init__(a, b)
30 self.a = a
31 self.b = b
32
33 def execute(self):
34 return self.a - self.b
35
36
37class NoneCmd(CalcCmdAbs):
38 name = "None Command"
39
40 def execute(self):
41 print("Invalid Command")
src/utils.py
1from .commands import OPERATORS, NoneCmd
2
3
4def get_commands() -> dict:
5 return dict([cmd.name, cmd] for cmd in OPERATORS)
6
7
8def parse_commands(commands: dict, operation: str, *args):
9 command = commands.setdefault(operation, NoneCmd)
10 return command(*args)
src/tests.py
1import unittest
2
3from .utils import get_commands, parse_commands
4
5
6class TestCase(unittest.TestCase):
7
8 def setUp(self) -> None:
9 self.commands = get_commands()
10
11 def test_addition(self):
12 command = parse_commands(self.commands, "add", 1, 1)
13 self.assertEqual(command.execute(), 2, "Addition fail")
14
15 def test_subtraction(self):
16 command = parse_commands(self.commands, "subtract", 1, 1)
17 self.assertEqual(command.execute(), 0, "Subtraction fail")
© 2021 by Build From Zero. All rights reserved.
Theme by LekoArts