The Observer Pattern defines a one-to-many
dependency between objects so that when one
object changes state, all of its dependents are
notified and updated automatically.
The observer pattern consists of publishers and subscribers similar to a newspaper subscription,
where the publisher is also known as subject or observable and the subscribers are called observers.
The observer pattern provides an object design where subjects and observers are
loosely coupled because of the following reasons:
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.
With the observer pattern it is possible to pull or push data from the
observable whereas pull is considered more correct.
It is also important to note that you should not depend on a specific order of
notification for your observers.
Here is the interface of a subject that a concrete subject class needs to implement in order to
register, remove and notify observers.
As an example for a concrete subject the following weather data class is given.
It has a member ArrayList<Observer> that stores the currently registered observers.
When the notifyObservers() function gets called, which happens when some data of
the subject changes, the subject knows how to inform the observers because they all
implement the same interface.
The observers that implement this interface know about the subject, which allows them
to register themselves to be kept informed. This can be seen in the following
example that also implements another interface DisplayElement.
Another example of a observer implementation.
And the additional interface they use.
The following main WeatherStation class shows the observer pattern in use.
Starting this application results in the following output.
Comments