Java Observer observe with more than one watcher

Introduction

We can observe a class with more than one wather.

The following code creates two watchers for the Observable.


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

// This is the first observing class.
class Watcher1 implements Observer {
  public void update(Observable obj, Object arg) {
    System.out.println("update() called, count is " + ((Integer) arg).intValue());
  }/*from w  w w  .  j a  v  a 2s . c om*/
}

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

// This is the class being observed.
class BeingWatched extends Observable {
  public 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");
      }
    }
  }
}

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

    // add both observers
    observed.addObserver(observing1);
    observed.addObserver(observing2);

    observed.counter(10);
  }
}



PreviousNext

Related