关闭

Observable(观测) 示例

1188人阅读 评论(0) 收藏 举报

/*

Observable类用于创建可以观测到你的程序中其他部分的子类,当这种子类的对象发生变化时,观测类被通知。观测类必须实现定义了update()方法和Observer接口。当一个观测程序被通知到一个被观测对象的改变时,update()方法被调用。
一个被观测的对象必须符合两个简单规则:第一,如果它被改变了必须调用setChanged()方法。第二,当它准备通知观测程序它的改变时,必须调用notifyObserver()方法。

*/

//Demonstrate the Observable class and the Observer interface.
import java.util.*;
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!");
   }
  }
 }
}
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);
 }
}

/*

有多个对象可以用作观测程序,下面程序实现了两个观测类并且将每个类中的一个对象增加到BeingWatched观测程序列表中,第二个观测程序等待直到计数为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 obsrving 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 TwoObserversDemo{
 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);
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:609072次
    • 积分:8046
    • 等级:
    • 排名:第2719名
    • 原创:75篇
    • 转载:247篇
    • 译文:0篇
    • 评论:65条
    文章分类
    最新评论