ChildDadFeed.java(设计模式)

Posted on 2009-04-15 18:02  pual.k3  阅读(192)  评论(0)    收藏  举报

package Observer;

import java.util.ArrayList;
import java.util.List;

//import java.lang.Exception;

//事件类,用来响应事件
class WakenUpEvent{
  private long time;
  private String loc;
  private Child source;// 发出这件事的源对象

  public WakenUpEvent(long time,String loc,Child source){
   super();
  this.time = time;
  this.loc = loc;
  this.source = source;
  }
 
  public long getTime(){
        return time;
  }
 
  public void setTime(long time){
         this.time = time;
  }
 
  public String getLoc(){
          return loc;
  }
 
  public void setLoc(String loc){
          this.loc = loc;
  }
 
  public Child getSource(){
           return source;
  }

  public void setSource(Child source){
           this.source = source;
  }
}
//child类,并且在内部运行一个线程,激发事件的发生
class Child implements Runnable{
  //使用数组创建监听类
 private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>();
  // boolean wakenUp = false;
  
  public void addWakenUpListener(WakenUpListener l){
    wakenUpListeners.add(l);
  }
  void wakenUp(){
   for(int i=0; i<wakenUpListeners.size();i++){
    WakenUpListener l = wakenUpListeners.get(i);
    l.ActionToWakenUp(new WakenUpEvent(System.currentTimeMillis(),"bed",this));
   
   }
  }

  public void run(){
    try{
       Thread.sleep(3000);
    }catch(InterruptedException e){
       e.printStackTrace();
    }
     this.wakenUp();
  }


}
//Dad监听者类继承WakenUpListener接口
class Dad implements WakenUpListener{
  
  public void ActionToWakenUp(WakenUpEvent wue){
    System.out.println("Dad feeded");
  }

}
//Mom监听者类继承WakenUpListener接口
class Mom implements WakenUpListener{
 public void ActionToWakenUp(WakenUpEvent wue){
  System.out.println("Mom id here!");
 }    
}
class Dog implements WakenUpListener{
 public void ActionToWakenUp(WakenUpEvent wue){
  System.out.println("旺旺!!");
 }
}
//监听者接口,当添加新的监听者时,不用修改原来的代码,只需要添加一个新的实现即可
interface WakenUpListener{
 public void ActionToWakenUp(WakenUpEvent wue);
}
 public class ChildDadFeed{
   public static void main(String[] args){
     Child c = new Child();
     c.addWakenUpListener(new Dad());
     c.addWakenUpListener(new Mom());
     c.addWakenUpListener(new Dog());
     new Thread(c).start();
     }
}
 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3