03使用jdk提供类实现观察者模式(三)

来源:互联网 发布:淘宝卖家快速升心 编辑:程序博客网 时间:2024/06/08 09:17

1.jdk默认对观察者模式提供了支持

   被观察着继承Observable

    观察者实现Observer接口

 

    被观察者通过调用notifyObservers()方法通知观察者

 

2.代码实现

   /**

Java代码  收藏代码
  1.  * 被观察者  
  2.  * @author Administrator  
  3.  *  
  4.  */  
  5. public class Watched extends Observable {  
  6.   
  7.     public void count(int num){  
  8.           
  9.         for(;num>=0;num--){  
  10.             //通知之前一定要设定setChanged  
  11.             this.setChanged();  
  12.               
  13.             //this.notifyObservers();  
  14.               
  15.             //如果需要为观察者传递信息,调用此方法,observer 的update第二个参数就能接受  
  16.             this.notifyObservers(num);  
  17.               
  18.             try {  
  19.                 Thread.sleep(200);  
  20.             } catch (InterruptedException e) {  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.           
  25.     }  
  26. }  

 

 

Java代码  收藏代码
  1. public class Watcher implements Observer {  
  2.   
  3.     /** 
  4.      * arg0:被观查者对象 
  5.      * arg1:被观察者传递给观察者信息 
  6.      */  
  7.     @Override  
  8.     public void update(Observable arg0, Object arg1) {  
  9.         System.out.println("update....."+arg1);  
  10.     }  
  11.   
  12. }  

 

Java代码  收藏代码
  1. public class Watcher2 implements Observer {  
  2.   
  3.     @Override  
  4.     public void update(Observable arg0, Object arg1) {  
  5.         System.out.println("update2....."+arg1);  
  6.     }  
  7.   
  8. }  

 

   客户端

Java代码  收藏代码
  1. public class Main {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         Watched watched = new Watched();  
  8.         Observer watcher = new Watcher();  
  9.         watched.addObserver(watcher);  
  10.         Observer watcher2 = new Watcher2();  
  11.         watched.addObserver(watcher2);  
  12.           
  13.         /** 
  14.          * 那个观察者后被加入,那个观察者update方法就想执行 
  15.          */  
  16.         watched.count(10);  
  17.     }  
  18.   
  19. }  
 
原创粉丝点击