Best way to implement Java Observer pattern for complex properties

I'm trying to implement the Observer pattern using JDK Observer/Observable however I'm struggling to see the best way to use it on beans that contains beans as properties. Let me give you my concrete example:

My main bean that needs to be observed for changes (in any of it's 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 anything in the ChildBean it won't trigger any change in the MainBean:

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

The more obvious solution I thought would be to make the ChildBean an Observable as well, and make the MainBean an Observer of the ChildBean. However that means I would need to explicitly call notifyObservers on the ChildBean, like such:

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

Should I even call notifyObservers() on the mainBean? Or should the call on the complexProperty cascade and trigger a notifyObservers() call in the mainBean?

Is this the proper way to do this, or are there easier ways?

Answers


Your Observables need to call notifyObservers whenever any of their properties change.

In this example:

mainBean would be an Observer of the Observable complexProperty.

complexProperty would have to call notifyObservers any time any of it's state changed.

If mainBean is also an Observable, it's update method (where it receives the notification from complexProperty or any other member Observable) would have to call notifyObservers to bubble this event up the structure.

mainBean should not be responsible for calling complexProperty.notifyObservers. complexProperty should do that. It should only call notifyObservers on itself.


If you want your MainBean to react when properties on your ChildBeanare modified, you should make the child an Observable.

Your setSomeProperty(...) should then notifyObservers after the property has been set.


Need Your Help

Creating a file name as a timestamp in a batch job

windows batch-file cmd timestamp

We have a batch job that runs every day and copies a file to a pickup folder. I want to also take a copy of that file and drop it into an archive folder with the filename

Try catch trouble in netbeans

if-statement netbeans hashmap try-catch

I'm trying to create a search engine that gets information from my SQL database. Right now I'm struggling to make the combobox and textfield work. So far I can only make the first part of the code ...