2 from pprint
import pformat
4 class Observer(object):
5 '''Observers receive notify(*attributes) messages from their
6 subjects whenever new data arrives. This notify() message signifies
7 that an observer should update its internal state/view.'''
9 def __init__(self
, model
):
11 self
.model
.add_observer(self
)
13 self
.__attribute
_adapter
= {}
18 self
.model
.remove_observer(self
)
20 def set_debug(self
, enabled
):
21 self
.__debug
= enabled
23 def notify(self
, *attributes
):
24 '''Called by the model to notify Observers about changes.'''
25 # We can be notified about multiple attribute changes at once
26 for attr
in attributes
:
28 if attr
not in self
.__subjects
: continue
30 # The new value for updating
32 notify
= model
.get_notify()
33 model
.set_notify(False)
34 value
= model
.getattr(attr
)
36 # Allow lazy model to observer attributes renames
37 if attr
in self
.__attribute
_adapter
:
38 attr
= self
.__attribute
_adapter
[attr
]
40 # Call the concrete observer's notification method
41 self
.subject_changed(attr
, value
)
43 model
.set_notify(notify
)
45 if not self
.__debug
: continue
46 print("Objserver::notify("+ pformat(attributes
) +"):")
49 def subject_changed(self
, attr
, value
):
50 '''This method handles updating of the observer/UI.
51 This must be implemented in each concrete observer class.'''
53 msg
= 'Concrete Observers must override subject_changed().'
54 raise NotImplementedError, msg
56 def add_subject(self
, model_attr
):
57 self
.__subjects
.append(model_attr
)
59 def add_attribute_adapter(self
, model_attr
, observer_attr
):
60 self
.__attribute
_adapter
[model_attr
] = observer_attr