1 from abc import ABCMeta, abstractmethod
2
3
4 -class Receiver(object, metaclass=ABCMeta):
5 """
6 Abstract receiver class as part of the Command pattern.
7
8 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage}
9 - External Command Pattern documentation: U{https://en.wikipedia.org/wiki/Command_pattern}
10 """
11 - def action(self, name, *args, **kwargs):
12 """
13 Delegates which method to be called for a desired action.
14
15 @param name: The name of the action to execute.
16 @type name: str
17 @param args: Any arguments for the action.
18 @param kwargs: Any keyword arguments for the action.
19 """
20 try:
21 return getattr(self, name)(*args, **kwargs)
22 except AttributeError:
23 raise AttributeError('Invalid Action.')
24
25
26 -class Command(object, metaclass=ABCMeta):
27 """
28 Abstract Command class as part of the Command pattern.
29
30 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage}
31 - External Command Pattern documentation: U{https://en.wikipedia.org/wiki/Command_pattern}
32 """
34 """
35 Initialize a new command instance.
36
37 @param receiver: The receiver for this command to use.
38 @type receiver: Receiver
39 """
40 self._receiver = receiver
41
42 @abstractmethod
44 """
45 Abstract method for executing an action.
46 """
47 pass
48
49 @abstractmethod
51 """
52 Abstract method for unexecuting an action.
53 """
54 pass
55
56
57 -class Invoker(object, metaclass=ABCMeta):
58 """
59 Abstract Invoker class as part of the Command pattern.
60
61 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage}
62 - External Command Pattern documentation: U{https://en.wikipedia.org/wiki/Command_pattern}
63 """
65 """
66 Initialize a new Invoker instance.
67
68 @param valid_commands: A list of command classes this invoker can handle.
69 """
70 self._history = []
71 self._valid_commands = valid_commands
72
74 """
75 Execute a command.
76
77 @param command: A command for the invoker to execute.
78 @type command: Command
79 """
80 if command.__class__ not in self._valid_commands:
81 raise AttributeError('Invalid Command')
82 else:
83 self._history.append(command)
84 return command.execute()
85
87 """
88 Undo the last command.
89 """
90 return self._history.pop().unexecute()
91