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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值