Observer pattern:
There are 2 variants of it.
- Where Subjects informs all the observers as an when an event occurs
- The observer can query the subject, if an event occured or not.
I am thinking of any real-world examples, which are applicable for option 2 ?
I have used option 1, in one of my projects where there is any particular event (on my socket), all the observers which are registered for that event, gets notified.
The second version isn’t an observer at all. That’s simply polling.
What the Design Patterns book actually described, and what you maybe meant, is this:
A use case for the second approach:
The subject is a set of address book records. Whenever the address book is updated, the observers should be notified. However, the amount of changed data could potentially be rather large and not each of the observers needs all the data. So instead of pushing all the data, you just notify all observers (possibly passing the ‘this’ pointer of the subject as an argument in case the observers should be able to listen to multiple subjects at once) and then provide the new state via getters – that way, each observer can fetch just the information it needs. Like the observer which updates the ‘Number of addresses’ field in your GUI – it’s not interested in the actual names, just in the number of items.