|
Define a one-to-many dependency between objects so that when one object changes, all its dependents are notified and updated automatically. This pattern observes the change of one particular attribute and notifies all its dependents. It uses the Smalltalk change/update mechanism.
A common side-effect of partitioning a system into a collection of cooperating classes is the need to maintain consistency between related objects. You don't want to achieve consistency by making the classes tightly coupled, because that reduces their reusability.
Use the Observer pattern in any of the following situations:
An expression that gives the observed object. Usually this expression follows a relation and returns the connected object. The actual object (self or this) is used if the parameter is not set.
The code that should be executed upon changing of the observer. Can be left empty if a method should be called (see participant action (optional)).
The Observer pattern lets you vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or other observers.
Further benefits and liabilities of the Observer pattern include the following:
... self changed: #{attribute} with: newValue.
super update: anAspect with: newValue from: aSender. (anAspect = #{attribute}) ifTrue: [ {code} or {action} ]. ]. ... other aspects ... ^self
((self dependents includes: {source}) or: [ {source} isNil ]) ifFalse: [{source} addDependent: self] self {establish}