2013-02-27 67 views
21

我最近讀了Java的Observable類。我不明白的是:在通知觀察者(notifyObservers())之前,我必須調用setChanged()。 notifyObservers方法中有一個布爾值,它要求我們調用setChanged。這個布爾值的目的是什麼,爲什麼我必須調用setChanged()?爲什麼我在通知觀察者之前需要調用setChanged?

+1

值得一提的是此功能不經常出現在這種模式的其他再現,比如JavaBeans的事件/監聽器。 'Observer' /'Observable'是一對糟糕的類/接口。模式的重點在於重複,而不是指向特定的類。 – 2013-02-27 20:00:41

回答

0

setchanged()用作指示或用於更改狀態的標誌。如果它是真的,則notifyObservers()可以運行並更新所有的觀察者。如果它沒有調用setchanged(),那麼調用notifyObservers()並且不會通知觀察者。

1

可能的原因可能是setChanged()有一個受保護的修飾符。同時,notifyObservers()可以在任何地方被調用,即使是觀察者也是如此。從那以後,觀察者和觀察者可以通過這種機制相互作用。

0
public void notifyObservers(Object arg) { 
    /* 
    * a temporary array buffer, used as a snapshot of the state of 
    * current Observers. 
    */ 
    Observer[] arrLocal; 

    synchronized (this) { 
     /* We don't want the Observer doing callbacks into 
     * arbitrary Observables while holding its own Monitor. 
     * The code where we extract each Observable from 
     * the ArrayList and store the state of the Observer 
     * needs synchronization, but notifying observers 
     * does not (should not). The worst result of any 
     * potential race-condition here is that: 
     * 
     * 1) a newly-added Observer will miss a 
     * notification in progress 
     * 2) a recently unregistered Observer will be 
     * wrongly notified when it doesn't care 
     */ 
     if (!hasChanged()) 
      return; 

     arrLocal = observers.toArray(new Observer[observers.size()]); 
     clearChanged(); 
    } 

    for (int i = arrLocal.length-1; i>=0; i--) 
     arrLocal[i].update(this, arg); 
} 

的評論是什麼原因

相關問題