As I mentioned in my previous example for Strategy Design Pattern, that the design patterns are best understood with examples. Without wasting any more time, I’ll just define our simple problem.
We have a newspaper say, “GlobalTimes” (fictitious name). The newspapers usually have many readers. Now, the problem is to notify the news readers of every news that is published in the newspaper.
Here, one solution to the stated problem is to use a producer/consumer model, where the every article published in a newspaper will have to be showcased in a store. Here, whenever a reader feels like, can go and check for news updates. But, the problem with this model is, the readers will not be updated as soon as the news is published. Also, this model will result in polling by millions of readers. i.e. extra processing and delay too.
Thus, observer pattern will be more suitable here. Lets talk about the observer pattern and how it is preventing delays and extra processing due to polling. In observer pattern, the job of updating the readers will be done by the newspaper itself. Generalizing the statement,
“Producer/Subject will itself be responsible for notifying the change of state to the observers.”
Here, the news in the subject, and the news reader are the observers. As, soon as there is a new news published, the newspaper will notify all the readers about the new news that has been published. Since, the newspaper is dealing with the updating part. The processing reduces significantly at the reader’s end.
In this design pattern there are two behaviors that are implemented.
- Subject which implements the following methods.
a) subscribe(Observer o) – adds to the list of observers to be notified.
b) unsubscribe(Observer o) – removes an observer from the list of observers to be notified.
c) notifyObservers() – notifies all the observers about the update.
- Observer which implements the following methods.
a) update(Info info) – where info is the state about which the observer has to be notified. i.e. info = news in our example
Download the implemented code
Pros and Cons
- Eliminates the need for observer polling for the subject.
- A single event handles all the notifications.
- The subject holds the reference to all the observers. So, in case the observers are too many, a lot of memory is consumed in keeping references of all those observers.
- In case, one observer is not needed any more, but it hasn’t unsubscribed yet. Then the reference with the subject will not allow the memory allocated to the observer to be garbage collected, resulting in memory leaks.