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?
source share