Reputation: 1570
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.
Upvotes: 1
Views: 230
Reputation: 691675
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.
Upvotes: 2
Reputation: 23001
The Subject is an object which controls some event or has some property which the Observers are interested in. The Observers register themselves with the Subject to express that interest, and the Subject keeps a list of those registered Observers.
When the Subject's property changes, or the event of interest occurs, the Subject iterates through its list of registered Observers and notifies them of the change or event.
The specifics of how the Observers are notified can vary. It may be that they have a well known method that gets called. It may be that they specify a custom method that they want called, which they specify as part of the registration process.
Upvotes: 1