forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver.py
More file actions
Latest commit
76 lines (60 loc) · 1.77 KB
/
Copy pathobserver.py
File metadata and controls
76 lines (60 loc) · 1.77 KB
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
'''http://code.activestate.com/recipes/131499-observer-pattern/'''
classSubject:
def__init__(self):
self._observers= []
defattach(self, observer):
ifnotobserverinself._observers:
self._observers.append(observer)
defdetach(self, observer):
try:
self._observers.remove(observer)
exceptValueError:
pass
defnotify(self, modifier=None):
forobserverinself._observers:
ifmodifier!=observer:
observer.update(self)
# Example usage
classData(Subject):
def__init__(self, name=''):
Subject.__init__(self)
self.name=name
self.data=0
defsetData(self, data):
self.data=data
self.notify()
defgetData(self):
returnself.data
classHexViewer:
defupdate(self, subject):
print('HexViewer: Subject %s has data 0x%x'% (subject.name, subject.getData()))
classDecimalViewer:
defupdate(self, subject):
print('DecimalViewer: Subject %s has data %d'% (subject.name, subject.getData()))
# Example usage...
defmain():
data1=Data('Data 1')
data2=Data('Data 2')
view1=DecimalViewer()
view2=HexViewer()
data1.attach(view1)
data1.attach(view2)
data2.attach(view2)
data2.attach(view1)
print("Setting Data 1 = 10")
data1.setData(10)
print("Setting Data 2 = 15")
data2.setData(15)
print("Setting Data 1 = 3")
data1.setData(3)
print("Setting Data 2 = 5")
data2.setData(5)
print("Detach HexViewer from data1 and data2.")
data1.detach(view2)
data2.detach(view2)
print("Setting Data 1 = 10")
data1.setData(10)
print("Setting Data 2 = 15")
data2.setData(15)
if__name__=='__main__':
main()