Search code examples
oopdesign-patternsobserver-pattern

Observer pattern-The subject keeps track of the items to be observed by the observer


Observer pattern-
Assumption:

  • Out of the 10 items, the observer only wants to be subscribed to 3.
  • Subject calls a function of the observer to let him know that there are some updates.

Now, is it subject's responsibility to send the updates pertaining to only 3 items to the observer?
OR
Subject can simply tell the observer that there are updates - go fetch whichever you want out of 10?

Which is the correct way out? Does it matter?


Solution

  • It's the Subject to keep a list of Observers who are interested in this subject, and notify these Observers by calling its update method. Observer does NOT keep a list of subjects which it is interested in.

    Based on this, when a subject is updated, the subject will call the update(..) method or something similar of those Observers in its list. subject can either encapsulate the changes in an object as a parameter of the method, Or pass the this object of this subject (observers get the interested data by calling subject's methods themselves).