Package smartcard :: Module Observer
[hide private]
[frames] | no frames]

Source Code for Module smartcard.Observer

 1  """ 
 2  from Thinking in Python, Bruce Eckel 
 3  http://mindview.net/Books/TIPython 
 4   
 5  Class support for "observer" pattern. 
 6   
 7  The observer class is the base class 
 8  for all smartcard package observers. 
 9   
10  Known subclasses: 
11          smartcard.ReaderObserver 
12   
13  """ 
14   
15  from smartcard.Synchronization import * 
16   
17   
18 -class Observer:
19
20 - def update(observable, arg):
21 '''Called when the observed object is 22 modified. You call an Observable object's 23 notifyObservers method to notify all the 24 object's observers of the change.''' 25 pass
26 27
28 -class Observable(Synchronization):
29
30 - def __init__(self):
31 self.obs = [] 32 self.changed = 0 33 Synchronization.__init__(self)
34
35 - def addObserver(self, observer):
36 if observer not in self.obs: 37 self.obs.append(observer)
38
39 - def deleteObserver(self, observer):
40 self.obs.remove(observer)
41
42 - def notifyObservers(self, arg=None):
43 '''If 'changed' indicates that this object 44 has changed, notify all its observers, then 45 call clearChanged(). Each observer has its 46 update() called with two arguments: this 47 observable object and the generic 'arg'.''' 48 49 self.mutex.acquire() 50 try: 51 if not self.changed: 52 return 53 # Make a local copy in case of synchronous 54 # additions of observers: 55 localArray = self.obs[:] 56 self.clearChanged() 57 finally: 58 self.mutex.release() 59 # Update observers 60 for observer in localArray: 61 observer.update(self, arg)
62
63 - def deleteObservers(self):
64 self.obs = []
65
66 - def setChanged(self):
67 self.changed = 1
68
69 - def clearChanged(self):
70 self.changed = 0
71
72 - def hasChanged(self):
73 return self.changed
74
75 - def countObservers(self):
76 return len(self.obs)
77 78 synchronize(Observable, 79 "addObserver deleteObserver deleteObservers " + 80 "setChanged clearChanged hasChanged " + 81 "countObservers") 82 #:~ 83