Have you ever been subscribed to the newsletter? When the author publishes the new issue, it comes straight to your inbox. You can always choose to unsubscribe too.
Why am I asking? Chances are that you’re already familiar with the pattern I’m going to describe today – the observer pattern.
Observer pattern allows creating a structure that allows objects (observers or publishers) to inform about their state to change other objects (observables or subscribers or subjects) in a loosely coupled way.
Let’s rephrase the definition of the observer pattern basing on the famous GoF book:
Observer pattern – defines one-to-many relationship between objects in such a way, that when the object changes his state, then all of his dependent objects are notified and updated
Example – weather station
Let’s take a weather station as an example for the demonstration of the observer pattern.
So let’s consider there’s a station which measures the weather parameters. The station can have multiple displays (subscribers), which will be refreshed (notified) whenever the station changes its state. When the state of the displays will be updated, their goal is to display the freshest data.
At first, we’re going to provide common interfaces to describe the communication between the observer (publisher) and observables (subscribers) objects.
As we can see, we have:
- Publisher – this is the observer interface with the ability to register or remove (subscribe or unsubscribe) the observable objects and with the method for all
- WeatherSubscriber – this is the observable interface with the update method
- Display – additional interface defining displaying behavior
And the implementation of the Publisher interface:
CurrentConditionsDisplay class is the Subscriber and Display interfaces implementation:
The observer in action – test
Let’s take a look at the simple test cases:
Try it yourself! As always the code is available on GitHub.
The main disadvantage of this pattern is the necessity of the subscribers’ registration.
Ralph Johnson one of the GoF members describes it in the conference talk about the design patterns. He explains it with the example of the mobster and the FBI agent.
Does the former inform the latter when he’s going to rob a bank in the real-world scenario?
If you’re looking for a way to notify the objects about the changes then the observer pattern can be a good, loosely coupled solution.
Other ways to implement the Observer pattern in Kotlin:
- using built-in delegate
- using java.util.Observable interface