|
1
|
|
|
from abc import ABC, abstractmethod, ABCMeta |
|
2
|
|
|
|
|
3
|
|
|
__all__ = ['GenericMediator', 'BaseComponent'] |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
class Mediator(ABC): |
|
7
|
|
|
""" |
|
8
|
|
|
The Mediator interface declares a method used by components to notify the |
|
9
|
|
|
mediator about various events. The Mediator may react to these events and |
|
10
|
|
|
pass the execution to other components. |
|
11
|
|
|
""" |
|
12
|
|
|
@abstractmethod |
|
13
|
|
|
def notify(self, sender: object, event: str) -> None: |
|
14
|
|
|
"""[summary] |
|
15
|
|
|
|
|
16
|
|
|
Args: |
|
17
|
|
|
sender (object): [description] |
|
18
|
|
|
event (str): [description] |
|
19
|
|
|
""" |
|
20
|
|
|
raise NotImplementedError |
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
class GenericMediator(Mediator, metaclass=ABCMeta): |
|
24
|
|
|
r"""Abstract Mediator class that automatically configures components received as \*args through the constructor.""" |
|
25
|
|
|
def __new__(cls, *components, **kwargs): |
|
26
|
|
|
generic_mediator = super().__new__(cls) |
|
27
|
|
|
for i, component in enumerate(components): |
|
28
|
|
|
setattr(generic_mediator, f'_component{i+1}', component) |
|
29
|
|
|
getattr(generic_mediator, f'_component{i+1}').mediator = generic_mediator |
|
30
|
|
|
return generic_mediator |
|
31
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
class BaseComponent: |
|
34
|
|
|
""" |
|
35
|
|
|
The Base Component provides the basic functionality of storing a mediator's |
|
36
|
|
|
instance inside component objects. |
|
37
|
|
|
""" |
|
38
|
|
|
|
|
39
|
|
|
def __init__(self, mediator: Mediator = None) -> None: |
|
40
|
|
|
self._mediator = mediator |
|
41
|
|
|
|
|
42
|
|
|
@property |
|
43
|
|
|
def mediator(self) -> Mediator: |
|
44
|
|
|
return self._mediator |
|
45
|
|
|
|
|
46
|
|
|
@mediator.setter |
|
47
|
|
|
def mediator(self, mediator: Mediator) -> None: |
|
48
|
|
|
self._mediator = mediator |
|
49
|
|
|
|