Observable(观测) 示例

/*

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值