我想使用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