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

的评论是什么原因

相关问题