java内置观察者模式学习小实例

package desginpattern.obverser;

/* Demonstrate the Observable class and the
Observer interface.
NOTES:
 被观察者的设计:
  1.扩展Observable类.
  2.如果它已经改变,必须调用setChanged()方法.
  3.当它准备通知观察者时,必须调用notifyObserver(Object obj)或notifyObserver()方法,这将导致观察者的update()方法调用.
 观察者的设计:
  1.实现Observer接口.
  2.改写此接口的唯一方法: void update(Observable observOb, Object arg)
  3.参数observOb是被观察对象,arg是观察者传递过来的对象,此时可对它进行相应的处理.

*/

import java.util.*;

//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 {
 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 ObserverDemo {
 public static void main(String args[]) {
  BeingWatched observed = new BeingWatched();
  Watcher observing = new Watcher();

  /* Add the observing to the list of observers for
   observed object.  */
  observed.addObserver(observing); //把观察者(如果有多个)都添加进被观察者的订阅列表中.

  observed.counter(10);
 }
}

 

你可能感兴趣的:(java,设计模式,thread,编程)