ChildDadFeed.java(设计模式)

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值