File: Observer.py

package info (click to toggle)
pyscard 1.6.10-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,360 kB
  • ctags: 1,516
  • sloc: python: 6,387; ansic: 2,065; makefile: 2
file content (74 lines) | stat: -rw-r--r-- 2,027 bytes parent folder | download
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
"""
from Thinking in Python, Bruce Eckel
http://mindview.net/Books/TIPython

Class support for "observer" pattern.

The observer class is the base class
for all smartcard package observers.

Known subclasses:
        smartcard.ReaderObserver

"""

from smartcard.Synchronization import *

class Observer:
    def update(observable, arg):
        '''Called when the observed object is
        modified. You call an Observable object's
        notifyObservers method to notify all the
        object's observers of the change.'''
        pass

class Observable(Synchronization):
    def __init__(self):
        self.obs = []
        self.changed = 0
        Synchronization.__init__(self)

    def addObserver(self, observer):
        if observer not in self.obs:
            self.obs.append(observer)

    def deleteObserver(self, observer):
        self.obs.remove(observer)

    def notifyObservers(self, arg=None):
        '''If 'changed' indicates that this object
        has changed, notify all its observers, then
        call clearChanged(). Each observer has its
        update() called with two arguments: this
        observable object and the generic 'arg'.'''

        self.mutex.acquire()
        try:
            if not self.changed:
                    return
            # Make a local copy in case of synchronous
            # additions of observers:
            localArray = self.obs[:]
            self.clearChanged()
        finally:
            self.mutex.release()
        # Update observers
        for observer in localArray:
            observer.update(self, arg)

    def deleteObservers(self):
            self.obs = []
    def setChanged(self):
            self.changed = 1
    def clearChanged(self):
            self.changed = 0
    def hasChanged(self):
            return self.changed
    def countObservers(self):
            return len(self.obs)

synchronize(Observable,
    "addObserver deleteObserver deleteObservers " +
    "setChanged clearChanged hasChanged " +
    "countObservers")
#:~