Demonstrate the Observable class and the Observer interface. : Observable and Observer « Design Pattern « Java Tutorial

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--) {
      notifyObservers(new Integer(period));
      try {
      } catch (InterruptedException e) {
        System.out.println("Sleep interrupted");


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



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