-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathobserver_presi.py
87 lines (61 loc) · 2.19 KB
/
observer_presi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from observer.observer_pattern import Observable, Observer
class Elf:
name = 'Galadriel'
def nall_nin(self):
print('Elf says: Calling the Overlord ...')
class Dwarf:
def estver_narho(self):
print('Dwarf says: Calling the Overlord ...')
class Human:
def ring_mig(self):
print('Human says: Calling the Overlord ...')
class MinionAdapter(Observable):
_initialised = False
def __init__(self, minion, **adapted_methods):
super().__init__()
self.minion = minion
for key, value in adapted_methods.items():
func = getattr(self.minion, value)
self.__setattr__(key, func)
self._initialised = True
def __getattr__(self, attr):
return getattr(self.minion, attr)
def __setattr__(self, key, value):
if not self._initialised:
super().__setattr__(key, value)
else:
setattr(self.minion, key, value)
self.notify_observer(key=key, value=value)
class MinionFacade:
minion_adapters = None
@classmethod
def create_minions(cls):
print('Creating minions ...')
cls.minion_adapters = [
MinionAdapter(Elf(), call_me='nall_nin'),
MinionAdapter(Dwarf(), call_me='estver_narho'),
MinionAdapter(Human(), call_me='ring_mig')
]
@classmethod
def summon_minions(cls):
print('Summoning minions ...')
for adapter in cls.minion_adapters:
adapter.call_me()
@classmethod
def monitor_elves(cls, observer):
cls.minion_adapters[0].add_observer(observer)
print('Added an observer to the Elves!')
@classmethod
def change_elves_name(cls, new_name):
print('Changing the Elves name ...')
cls.minion_adapters[0].name = new_name
print('Elves name changed!')
class EvilOverlord(Observer):
def update(self, obj, *args, **kwargs):
print('The Evil Overlord received a message!')
print(f'Object: {obj}, Args: {args}, Kwargs: {kwargs}')
if __name__ == '__main__':
overlord = EvilOverlord()
MinionFacade.create_minions()
MinionFacade.monitor_elves(overlord)
MinionFacade.change_elves_name('Elrond')