我想使用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
可观察到的,以及,使MainBean
的ChildBean
的观察员。然而,这意味着我需要明确呼吁ChildBean
notifyObservers,像这样的:
...
mainBean.getComplexProperty().setSomeProperty("new value");
mainBean.getComplexProperty().notifyObservers();
mainBean.notifyObservers();
...
我应该甚至呼吁mainBean notifyObservers()?或者应该调用complexProperty级联并触发mainBean中的notifyObservers()调用?
这是做到这一点的正确方法,还是有更简单的方法?
有趣 - 我只花了一整天的时间写一个'ObservableCollection','ObservableSet'和'ObservableMap'来挂钩'ChangePropertySupport'。非常类似于这个! :-)在bean构造期间,我用'final ObservableCollection's注册了'CollectionListener's,它对任何变化执行'firePropertyChange'。这样,bean上的所有'PropertyChangeListener'都可以看到'Collection'属性的更改。 – fommil 2012-08-03 23:15:46