2013-02-27 13 views
21

私は最近、JavaのObservableクラスについて読んだことがあります。私が理解していないことは、オブザーバ(notifyObservers())に通知する前に、setChanged()を呼び出す必要があります。 notifyObserversメソッド内には、setChangedを呼び出す必要があるブール値があります。ブール値の目的は何ですか?setChanged()を呼び出さなければならない理由は何ですか?なぜオブザーバに通知する前にsetChangedを呼び出す必要がありますか?

+1

それは、この機能は、多くの場合、インスタンスJavaBeansのイベント/リスナーのために、このパターンの他のレンディションに表示されていないことは注目に値しますです。 'Observer' /' Observable'はクラス/インターフェースの酷いペアです。パターンのポイントは、特定のクラスを参照するのではなく、繰り返すことです。 –

答えて

22

長い治療では、setChanged()を数回呼び出すことができますが、最後には1回だけnotifyObservers()とします。終了する前に、内部的な理由でロールバックを決定した場合は、clearChanged()に電話することを選択することができます。後者の場合、notifyObservers()は効果がありません。

0

状態を変更するための指示またはフラグとしてsetchanged()が使用されます。 trueの場合、notifyObservers()はすべてのobserversを実行して更新できます。notifyObservers()はsetchanged()を呼び出さずに呼び出され、オブザーバは通知されません。

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); 
} 

コメントが理由

関連する問題