Observer Pattern
Publishers + Subscribers = Observer Pattern
We call the publisher the SUBJECT, and the subscribers the OBSERVERS.
The Observer Pattern defines a one-to-many dependency between objects to that when one object changes state, all of its dependents are notified and updated automatically.
The power of Loose Coupling
When two objects are loosely couples, they can interact but have very little knowledge of each other.
The Observer Pattern provides an object design where subjects and observers are loosely coupled.
Why?
- The only thing the subject knows about an observer is that it implements a certain interface (the Observer interface).
- We can add new observers at any time.
- We never need to modify the subject to add new types of observers.
- We can reuse subjects or observers independently of each other.
- Changes to either the subject or an observer will not affect the other.
Design Principle:
Strive for loosely coupled designs between objects that interact.
Loosely coupled designs allow us to build flexible OO systems that can handle change because they minimize the interdependency between objects.
How Java's built-in Observer Pattern works
For an object to become an observer...
call addObserver() on any observable object
remove yourself as an observer just call deleteObserver()
For the Observerable to send notifications...
First of all you need to be Observable by extending the java.util.Observable superclass.
1. You first much call the setChanged() method to signify that the state has changed in your object.
2. Then call one of two notifyObservers() methods: either
notifyObservers() or
notifyObservers(object arg)
For an Observer to receive notifications...
update(Observable o, Object arg)
Tools for your Design Toolbox
- OO Principles
Strive for loosely coupled designs between objects that interact.
- OO Patterns
Observer - defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically