实现复杂属性的Java观察者模式的最佳方法

4
我正在尝试使用JDK Observer/Observable实现观察者模式,但是我很难看到在包含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也设置为可观察对象,并使MainBean成为ChildBean的观察者。但这意味着我需要明确地在ChildBean上调用notifyObservers,如下所示:

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

我应该在mainBean上调用notifyObservers()吗?还是应该在complexProperty上进行级联调用,并在mainBean中触发notifyObservers()呢?

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


1
有趣的是,我整天都在编写ObservableCollectionObservableSetObservableMap,以便与ChangePropertySupport连接。非常类似于这个!:-) 在bean构造期间,我使用final ObservableCollection注册CollectionListener,它们对任何更改执行firePropertyChange。这样,bean上的所有PropertyChangeListener都可以看到Collection属性的更改。 - fommil
2个回答

2

当您的可观察对象的属性发生变化时,需要调用notifyObservers方法。

例如:

mainBean将是Observable complexProperty的观察者。

complexProperty必须在其状态发生任何改变时调用notifyObservers。

如果mainBean也是一个Observable,那么它的update方法(接收来自complexProperty或任何其他成员Observable的通知的方法)必须调用notifyObservers以将此事件向上传递给结构。

mainBean不应负责调用complexProperty.notifyObservers。complexProperty应该这样做。它只应该在自身上调用notifyObservers。


0
如果您希望您的MainBeanChildBean的属性被修改时做出反应,那么您应该将子对象设置为Observable
然后,在您的setSomeProperty(...)方法中,属性被设置后应该调用notifyObservers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接