OOP Design Patterns 2 - Observer Pattern
The observer pattern defines a one to many dependencies between objects so that when one object changes state all of its dependents are notified and updated automatically
This provides an object design where subjects and observers are loosely coupled: They interact but have very little knowledge of each other making the system very flexible. This comes handy because
- we never have to modify the subject class to add new observer types. All we need to do is implement the Observer interface in the new class and register as an Observer.
- We can also easily reuse Subject or the Observer independently.
- Changes to either will not affect the other.
Since Java has a built-in Observer Pattern, let's look at it.
Subject will have to extend the java.util.Observable class and inherits add, remove and notify methods. To send notifications Observable must call setChanged() method to signify the state has changed and then call notifyObervers() method
Observers implement the java.util.Observer class and overrides the update() method
However, Java Observable/Observer implementation of the pattern violates the principle ‘prefer composition over inheritance’ and ‘program to an interface, not an implementation’ with how Observable is used.
Note that we shouldn't depend on notification order when using this pattern.