You are on page 1of 10

Observer Design Pattern

By Eric Perret
Pages 372-380 in Applying
UML and Patterns

1
What we are covering.
 Definition
 Example
 Example using code
 Why it is a good idea to use the
pattern.
 Summary

2
What is an Observer?
 The Observer design pattern, or more
accurately some implementation of this
pattern, is used to assure consistency
between different objects.
 AKA Publish-Subscribe

3
What does this really mean.
 When an object changes state, all of
the objects that need to know about it
are notified and updated automatically.

4
Example…
 Let the state of an object "B" depend on the
state of an object "A". Whenever the state of
object "A" changes, "B" has to recompute its
state in order to remain consistent with "A".
 The observer design pattern supports such
dependencies and at the same time tries to
reduce the coupling between the object that
changes (the publisher) and the object that
needs a change notification (the subscriber).
5
Here's an example of the
interfaces in java-like code:
 public abstract interface Subject {
public abstract void
 The subject calls its
addObserver(Observer "notify" operation
observer); whenever it changes.
public abstract void "Notify" calls the
removeObserver(Observer
observer); "update" operation
}
public abstract void notify(); on each observer.
public abstract class Observer { The observers then
public abstract void update(); call back to the
} subject and update
themselves
accordingly.

6
Why Use the Pattern?
 State dependencies between objects are
unfavorable for several reasons.
 If we could model our problem domain as a
set of independent classes, we would get a
software system without state
dependencies.
 Coding and especially maintaining such a
system would be much easier. The
programmer could focus on single classes
only.
7
Summary
 Loosely couple objects in terms of
communication
 Publishers know about subscribers
only through an interface and
subscribers can register or de-register
dynamically with the publisher

8
Question, comments, theories,
or conundrums?
 Slides can be found here: http://
www.rpi.edu/~perree/sdd

9
References
 Applying UML and Patterns by Craig
Larman, 352-380
 On Using the Observer Design Pattern by
Constantin Szallies,
http://www.wohnklo.de/patterns/observer.ht
ml
 Observer Design Pattern by Stephen Lam,
http://sern.ucalgary.ca/courses/SENG/609.0
4/W98/lamsh/observerLib.html
10

You might also like