Best way to implement Java Observer pattern for complex properties

I am trying to implement an Observer pattern using the Observer / Observable JDK, but I am struggling to find a better way to use it on beans that contains beans as properties. Let me give you a specific example:

My main bean that needs to be watched for changes (in any of its properties) is ..

public class MainBean extends Observable { private String simpleProperty; private ChildBean complexProperty; ... public void setSimpleProperty { this.simpleProperty = simpleProperty; setChanged() } } 

.. however, when I want to set a new value for something in ChildBean , it will not cause any changes to MainBean:

 ... mainBean.getComplexProperty().setSomeProperty("new value"); ... 

The more obvious solution, I thought, was to make ChildBean Observable, as well as make MainBean Observer. However, this means that I will need to explicitly call notifyObservers in the ChildBean , for example:

 ... mainBean.getComplexProperty().setSomeProperty("new value"); mainBean.getComplexProperty().notifyObservers(); mainBean.notifyObservers(); ... 

Should I even call notifyObservers () on mainBean? Or do you need to call the complexProperty cascade and call the notifyObservers () call in mainBean?

Is this the right way to do this, or are there simpler ways?

+4
source share
2 answers

Your watchers should call notifyObservers whenever any of their properties change.

In this example:

mainBean will be the observer of the complex property Observable.

complexProperty would have to call notifyObservers at any time when any of its states changed.

If mainBean is also observable, its update method (where it receives a notification from complexProperty or any other observable member) should call notifyObservers to output this event by structure.

mainBean should not be held responsible for calling complexProperty.notifyObservers. complexProperty has to do this. It should only call notifyObservers on its own.

+2
source

If you want your MainBean respond when the properties of your ChildBean have changed, you must make the child an Observable .

Then your setSomeProperty(...) should notifyObservers after the property has been set.

0
source

All Articles