2012-08-03 60 views
4

我想使用JDK Observer/Observable实现观察者模式但是我很努力地看到在包含bean作为属性的bean上使用它的最佳方式。让我给你我的具体的例子:为复杂属性实现Java观察者模式的最佳方式

我需要更改待观察(在任何它的属性)是主要豆..

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

..however当我想设置一个新值在ChildBean什么也不会触发该MainBean任何变化:

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

更明显的解决方案,我认为将是使ChildBean可观察到的,以及,使MainBeanChildBean的观察员。然而,这意味着我需要明确呼吁ChildBean notifyObservers,像这样的:

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

我应该甚至呼吁mainBean notifyObservers()?或者应该调用complexProperty级联并触发mainBean中的notifyObservers()调用?

这是做到这一点的正确方法,还是有更简单的方法?

+1

有趣 - 我只花了一整天的时间写一个'ObservableCollection','ObservableSet'和'ObservableMap'来挂钩'ChangePropertySupport'。非常类似于这个! :-)在bean构造期间,我用'final ObservableCollection's注册了'CollectionListener's,它对任何变化执行'firePropertyChange'。这样,bean上的所有'PropertyChangeListener'都可以看到'Collection'属性的更改。 – fommil 2012-08-03 23:15:46

回答

0

如果你希望你的MainBean反应时,你的ChildBean被修改的属性,你应该使孩子的Observable

您的setSomeProperty(...)应该在属性设置后通知观察者。

2

只要其任何属性发生变化,您的观察者就需要调用notifyObservers。

在这个例子中:

mainBean将是可观测complexProperty的观察者。

complexProperty在任何时候都会调用notifyObservers的状态。

如果mainBean也是一个Observable,它的更新方法(它接收来自complexProperty或任何其他成员Observable的通知)必须调用notifyObservers才能将此事件向上展开。

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