2012-08-03 19 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。