We wrap up the season with the observer pattern and a review of what we have learned. This pattern is one that you probably have already encountered. Instead of an observer, you probably have heard it called a listener.
The Observer Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”
Thus, the observer pattern is precisely what the name implies. You assign an object to an observer, and when something changes in the observed object, the observer is notified. The key to this is that it is a one-to-many relationship where an object may have zero or more observers. The observed does not care about the observer; it just knows to keep that instance “informed” of changes.
Applying The Pattern
This pattern is another one that can end up producing two hierarchies. The observer hierarchy will likely start from an interface and then can be extended. We can add actions to the observer pattern or adjust the signatures. An action or notification may send a value with the notification but does not need to do so.
The observable object will also start from an interface. It will likely stay shallow if it is extended at all. However, you may have some different action/notification options or more than a simple register and de-register method for the observers. There might also be security or authentication required as part of the observer process.
Java, PHP, C#, etc.
This pattern sticks to the core features of a language. All you need to implement this is a base class (probably an interface) and support for inheritance. That leaves you almost identical implementation approaches in whatever language you choose to use.