08 BehavioralPatterns
08 BehavioralPatterns
Algorithms and the assignment of responsibilities among objects Describe not just patterns of objects or classes but also the patterns of communication between them Shift your focus away from flow of control to let you concentrate just on the way objects are interconnected Observer
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Applicability
An abstraction has two aspects, one dependent on the other. When changing one object requires changing others, and you dont know how many objects need changed. When an object needs to notify others without knowledge about who they are.
Subject *
<<interface>> Observer
observers update()
observerState := subject.getState()
ConcreteObserver update()
subject
Subject
Knows its observers, but not their real identity. Provides an interface for attaching/detaching observers. Defines an updating interface for objects that should be identified of changes.
Observer
ConcreteSubject
Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change.
Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with ConcreteSubject. Implements the Observer interface.
ConcreteObserver
Collaborations
ConcreteSubject notifies observers when changes occur. ConcreteObserver may query subject regarding state change.
5
Benefits
Can reuse subjects without reusing their observers and vice versa Observers can be added without modifying the subject All subject knows is its list of observers Subject does not need to know the concrete class of an observer, just that each observer implements the update interface Subject and observer can belong to different abstraction layers
Support for broadcast communication: subject sends notification to all subscribed observers
Liabilities
Observers are not necessarily aware of each other and must be careful about triggering updates Simple update interface requires observers to deduce changed item
7
Have the subject tell the observer who it is via the update interface The subject whenever its state changes The observers after they cause one or more state changes Some third party object(s)
Make sure the subject updates its state before sending out notifications How much info about the change should the subject send to the observers?
Can an observer also be a subject? What if an observer wants to be notified only after several subjects have changed state?
Use an intermediary object which acts as a mediator Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers
10
super(title); Panel tfPanel = new Panel(); tf.setText("0"); tfPanel.add(tf); add("North", tfPanel); Panel buttonPanel = new Panel(); Button incButton = new Button("Increment"); incButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { counter++; tf.setText(counter + ""); }
} ); buttonPanel.add(incButton);
11
buttonPanel.add(decButton); Button exitButton = new Button("Exit"); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); buttonPanel.add(exitButton); add("South", buttonPanel);
12
Where is the controller in this example? The controllers are the instances of the anonymous classes which handle the button presses.
13
14
buttonPanel.add(decButton); Button exitButton = new Button("Exit"); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); buttonPanel.add(exitButton); add("South", buttonPanel);
16
17
18
But we have a problem! When the model changes state, only one view updates! We need the Observer Pattern here!
19
20
21
22
23
24
25
Decouples a subject and its observers Widely used in Smalltalk to separate application objects from interface objects Known in the Smalltalk world as Model-View-Controller (MVC) Rationale:
the interface is very likely to change while the underlying business objects remain stable
Defines a subject (the Observable) that is observed Allows multiple observers to monitor state changes in the subject without the subject having explicit knowledge about the existence of the observers
Observer Subject Observer Observer
26
Developed at Xerox Parc to provide foundation classes for Smalltalk-80 The Model, View and Controller classes have more than a 10 year history Fundamental Principle
separate the underlying application MODEL (business objects) from the INTERFACE (presentation objects)
In Smalltalk, objects may have dependents When an object announces I have changed, its dependents are notified It is the responsibility of the dependents to take action or ignore the notification
27
setChanged()
Harry
hasChanged() True/false
28
Checking an Observable
public static void main (String args [ ] ) { Harry harry = new Harry (false); harry.updateMaritalStatus (true); if (harry.hasChanged() ) System.out.println ("Time to call harry");
29
addObserver (this)
Observer1
addObserver (observer2)
Observer2
Harry
Observer1
The superclass of all observable objects to be used in the Model View design pattern
Interface Defines the update() method that allows an object to observe subclasses of Observable Objects that implement the interface may be passed as parameters in:
addObserver(Observer o)
32