implements Observer : Observer « java.util « Java by API






implements Observer

/*
 * Output: 

update() called, count is 10
update() called, count is 9
update() called, count is 8
update() called, count is 7
update() called, count is 6
update() called, count is 5
update() called, count is 4
update() called, count is 3
update() called, count is 2
update() called, count is 1
update() called, count is 0
 *  
 */

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

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

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

public class MainClass {
  public static void main(String args[]) {
    BeingWatched observed = new BeingWatched();
    Watcher observing = new Watcher();

    observed.addObserver(observing);

    observed.counter(10);
  }
}
           
       








Related examples in the same category