-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathobserver.py
45 lines (30 loc) · 1.1 KB
/
observer.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
# ------------------------------
# Observer Design Pattern
# ------------------------------
# Define a one-to-many dependency between objects
# where a state change in one object results in all its dependents being notified and updated automatically.
class Subject:
def __init__(self):
self.__observers = []
def register(self, observer):
self.__observers.append(observer)
def notify(self, *args, **kwargs):
for observer in self.__observers:
observer.notify(self, *args, **kwargs)
class Observer1:
def __init__(self, subject):
subject.register(self)
def notify(self, subject, *args):
print(type(self).__name__,': Got', args, 'From', subject)
class Observer2:
def __init__(self, subject):
subject.register(self)
def notify(self, subject, *args):
print(type(self).__name__, ': Got', args, 'From', subject)
subject = Subject()
# ----------------------------
# Registers observer with subject
#--------------------------------
observer1 = Observer1(subject)
observer2 = Observer2(subject)
subject.notify('Notification.')