Design Patterns - Observer Pattern
Design Patterns - Observer Pattern
Observer Pattern
Observer Pattern
• Don’t miss out when something interesting (in your system)
happens!
• The observer pattern allows objects to keep other objects
informed about events occurring within a software system (or
across multiple systems)
• It’s dynamic in that an object can choose to receive or not receive
notifications at run-time
• Observer happens to be one of the most heavily used patterns in
the Java Development Kit
• and indeed is present in many frameworks
Observer Pattern – Example
Problems:
1. The number and type of displays may vary. These three displays
are hard coded with no easy way to update them.
Observer
3
Observers
Observer Pattern – In Action
Observer
1
Observer
3
Observers
Observer Pattern – In Action
Observer
1
Observer
3
Observers
Observer Pattern – In Action
Observer
1
At any point, an observer may
join or leave the set of observers
Observer
Subject
2
Observer
3
Observer
4
Observers
Observer Pattern
• The Observer Pattern defines a one-to-many dependency between a
set of objects, such that when one object (the subject) changes, all of
its dependents (observers) are notified and updated automatically
Observer Pattern – Benefits
• Observer affords a loosely coupled interaction between subject and
observer
• This means they can interact with very little knowledge about each other
• Consider
• The subject only knows that observers implement the Observer interface
• We can add/remove observers of any type at any time
• We never have to modify subject to add a new type of observer
• We can reuse subjects and observers in other contexts
• The interfaces plug-and-play anywhere observer is used
• Observers may have to know about the ConcreteSubject class if it provides
many different state-related methods
• Otherwise, data can be passed to observers via the update() method