An object may be observed by two or more observers. : Observable and Observer « Design Pattern « Java Tutorial






import java.util.Observable;
import java.util.Observer;

class Watcher1 implements Observer {
  public void update(Observable obj, Object arg) {
    System.out.println("update() called, count is " + ((Integer) arg).intValue());
  }
}

class Watcher2 implements Observer {
  public void update(Observable obj, Object arg) {
    if (((Integer) arg).intValue() == 0)
      System.out.println("Done");
  }
}

class BeingWatched extends Observable {
  void counter(int period) {
    for (; period >= 0; period--) {
      setChanged();
      notifyObservers(new Integer(period));
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        System.out.println("Sleep interrupted");
      }
    }
  }
}

class MainClass {
  public static void main(String args[]) {
    BeingWatched observed = new BeingWatched();
    Watcher1 observing1 = new Watcher1();
    Watcher2 observing2 = new Watcher2();

    observed.addObserver(observing1);
    observed.addObserver(observing2);

    observed.counter(10);
  }
}








34.2.Observable and Observer
34.2.1.Observable and Observer Objects
34.2.2.Demonstrate the Observable class and the Observer interface.
34.2.3.An object may be observed by two or more observers.
34.2.4.Demonstration of 'observer' pattern.
34.2.5.Watch What is Going On with the Observer Patterns
34.2.6.Timeout Observer