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