Java Observer interface

Introduction

The following code shows how to create an observable object.

It creates an observer class, called Watcher, that implements the Observer interface.

The class being monitored is called BeingWatched. It extends Observable.


/* Demonstrate the Observable class and the
   Observer interface.//w  w w . j  av  a2 s  .  c  om
*/

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

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

// 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();
    Watcher observing = new Watcher();

    observed.addObserver(observing);

    observed.counter(10);
  }
}



PreviousNext

Related