观察者模式

来源:互联网 发布:淘宝助理怎么修改价格 编辑:程序博客网 时间:2024/04/20 13:19

  2007-3-15                            阴天

   观察者模式,有两个角色:

  一是 被观察者角色  ,二是 观察者

  主要事件是: 被观察者若发生改变就要通知所有的观察者, 观察者对自身实施一些操作

  两个角色的内部结构:

 观察者 主要对自身的更新,更新的方法

 被观察者  主要维护一个容器(用于装观察者,两者是1对n的关系),添加观察者,删除观察者,通知所有观察

                  (此处用到 对抽相的编程,其实也就是多态)

下面是我的测试代码:

 抽相观察者
package com.dbss.pattern;

public interface WatchInterface {
 
 public void update();
 
 public void print();

}


被观察者(此处我没有进行抽相了)
package com.dbss.pattern;

import java.util.ArrayList;
import java.util.Iterator;

public  class Watched {
 
 private ArrayList list = new ArrayList();
 
 //注册Watch对相
 public void addWatch(WatchInterface obj){
  obj.print();//用于全局跟踪
  list.add(obj);
  
 }
 
 //册除Watch对相
 public void delWatch(){
  Iterator it =  getList().iterator();
        if(it.hasNext()){
   it.remove();
  }
 }
 
 //通知所有的Watch对相
 public void notifyWatchs(){
  Iterator it = getList().iterator();
  while(it.hasNext()){
   //注意此处的()用法
   ((WatchInterface)it.next()).update();
  }
 }
 
 //获取ArrayList对相的clone
 public ArrayList getList(){
  return (ArrayList)list.clone(); 
 }

}

//具体的观察者Watch1
package com.dbss.pattern;

public class Watch1 implements WatchInterface {

 // 在构造Watch对相时,就把引用加入到list中
 Watch1(Watched w){
  System.out.println("----create Watch1----");
  w.addWatch(this);
 }
 
 public void update(){
  System.out.println("Watch1:  update()");
 }
 
    // 用于全局跟踪
 public void print(){
  System.out.println("&&&&Watch1 is added to List&&&&");
 }
}


//具体的观察者Watch1
package com.dbss.pattern;

public class Watch2 implements WatchInterface {

 // 在构造Watch对相时,就把引用加入到list中
 Watch2(Watched w){
  System.out.println("++++create Watch2++++");
  w.addWatch(this);
 }
 
 public void update(){
  System.out.println("Watch2:  update()");
 }
 
    // 用于全局跟踪
 public void print(){
  System.out.println("^^^^Watch2 is added to List^^^^");
 }
}


//程序入口
package com.dbss.pattern;

public class Client {
 
 public static void main(String args[]){
  
  //创建一个被观察对相
  Watched watched = new Watched();
  
  //创建3个不同的观察对相,并加入容器中
  Watch1 w1 = new Watch1(watched);
  Watch2 w2 = new Watch2(watched);
  Watch3 w3 = new Watch3(watched);
  
  System.out.println("/n------------------------------");
  System.out.println("------------------------------/n");
  System.out.println("begin to notfiy all Watches");
  
  //通知所有的Watch
  watched.notifyWatchs();
    }
}

 

 


 

                  

 

原创粉丝点击