为复杂属性实现Java Observer模式的最佳方法

我正在尝试使用JDK Observer / Observable实现Observer模式,但是我很难看到在包含bean作为属性的bean上使用它的最佳方法.让我举一个具体的例子:

我的主要bean需要观察更改(在任何属性中)是..

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

..但是当我想为ChildBean中的任何东西设置一个新值时,它不会触发MainBean中的任何更改:

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

我认为更明显的解决方案是使ChildBean成为Observable,并使MainBean成为ChildBean的Observer.但是,这意味着我需要在ChildBean上显式调用notifyObservers,如下所示:

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

我应该甚至在mainBean上调用notifyObservers()吗?或者应该在complexProperty级联上调用并在mainBean中触发notifyObservers()调用?

这是正确的方法,还是有更简单的方法?

最佳答案 只要任何属性发生变化,您的Observable都需要调用notifyObservers.

在这个例子中:

mainBean将是Observable complexProperty的Observer.

complexProperty必须在任何状态发生变化时调用notifyObservers.

如果mainBean也是一个Observable,它的update方法(它从complexProperty或任何其他成员Observable接收通知)必须调用notifyObservers来向结构中冒泡这个事件.

mainBean不应该负责调用complexProperty.notifyObservers. complexProperty应该这样做.它应该只调用notifyObservers本身.

点赞