Search code examples
oopdesign-patternsobserver-pattern

Observer pattern - observer creation


I'm learning about design patterns and I have stumbled upon a question I really don't know how to find an answer to. In the observer design pattern class diagrams, I have seen that a Concrete Observer usually has a reference to the Subject. But, who sets the value of that reference? And how Attaching function gets called? Do observers call it themselves according to the subject reference they have, or somebody else sets the subject and then attaches the observer to the subject? I've looked for examples, but I'm still having troubles finding the best way to implement this.


Solution

  • The observer is the component that wants to be notified about changes or events of the subject. It decides to observe the subject and adds itself to the list of observers that the subject maintains.

    The typical use-case is a graphical panel containing a button. The graphical panel creates a button and adds it to itself. And it wants to display a dialog box every time the button is clicked. So it adds itself as an observer of the button, and the button notifies the panel when it's clicked.

    In this example, the observer creates the object it observes. But there are situations where that is not the case, and when the reference to the subject is passed as an argument to its constructor or one of its methods. This is irrelevant to the principle of the observer pattern itself.