六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 32|回复: 0

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

[复制链接]

升级  12.67%

17

主题

17

主题

17

主题

秀才

Rank: 2

积分
69
 楼主| 发表于 2013-2-3 14:36:21 | 显示全部楼层 |阅读模式
package desginpattern.obverser;/* Demonstrate the Observable class and theObserver 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); }} 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表