twoobservers.java~4~

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

JAVA~4~
75
字号
package 实现两个观测类;

/**
 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
 Done
 update() called, count is 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 + -
显示快捷键?