twoobservers.java~3~

来自「java2参考大全上的例子的源码和自己的理解.」· JAVA~3~ 代码 · 共 68 行

JAVA~3~
68
字号
package 实现两个观测类;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: </p>
 * @author not attributable
 * @version 1.0
 */

/* An object may be observed by two or more
   observers.
 */

import java.util.*;

// 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());
  }
}

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

// This is the class being observed.
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 TwoObservers {
  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);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?