2

I am trying to currently get a good grasp on the Observer design pattern, but I am stuck wondering about one specific issue. In the examples I have been able to find of implementation, they are all rather basic in terms of having a specifically designed state.

For instance, the "subject" class that is being observed only has a single state or variable that is being reported to any other classes observing it. My question is, what happens when you have a class representing a large or complex data structure?

Lets say I have multiple variables on a single class, and implement it as observable. Then setup something to watch it for changes in a specific variable. Does the observing class need to be notified every time something changes not related to what it is interested in? If so, do I have to write an update method for each type of variable that could potentially be observed? Or should I be writing an observer for every single variable on the class that could be observed?

Any clarity on this matter is appreciated.

1

1 Answer 1

2

You could have a single observable interface that allows subscribing by property name or even using regex. Using a map instead of a list to hold observers should work. You talk about observing 'variables' which may not mean much but you should be careful to avoid think in terms of concrete implementation details when designing interactions between classes. You really to create your interface in terms observing abstract properties.

One note of caution: the observer pattern is associated with memory leak problems because the observed object will keep a reference to the observer until you remove it. Consider using weak references for your observers to avoid having to worry about removing observers in order to release them to garbage collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.