Java 事件监听

Person.class

//事件源
public class Person {
	  /**
	  * @Field: listener
	  *     在Person类中定义一个PersonListener变量来记住传递进来的监听器
	  */
	  private PersonListener listener;
	 
	  /**
	  * @Method: eat
	  * @Description: 设计Person的行为:吃
	  *
	  */
	  public void eat() {
	    if (listener != null) {
	      /**
	       * 调用监听器的doeat方法监听Person类对象eat(吃)这个动作,将事件对象Event传递给doeat方法,
	       * 事件对象封装了事件源,new Event(this)中的this代表的就是事件源
	       */
	      listener.doeat(new Event(this));
	    }
	  }
	 
	  /**
	  * @Method: run
	  * @Description: 设计Person的行为:跑
	  *
	  */
	  public void run() {
	    if (listener != null) {
	      /**
	       * 调用监听器的dorun方法监听Person类对象run(跑)这个动作,将事件对象Event传递给doeat方法,
	       * 事件对象封装了事件源,new Event(this)中的this代表的就是事件源
	       */
	      listener.dorun(new Event(this));
	    }
	  }
	 
	  /**
	  * @Method: registerListener
	  * @Description: 这个方法是用来注册对Person类对象的行为进行监听的监听器
	  *
	  * @param listener
	  */
	  public void registerListener(PersonListener listener) {
	    this.listener = listener;
	  }
	}
	 
	/**
	* @ClassName: PersonListener(事件监听器)
	* @Description: 设计Person类(事件源)的监听器接口
	*
	*/
	interface PersonListener {
	 
	  /**
	  * @Method: doeat
	  * @Description: 这个方法是用来监听Person对象eat(吃)这个行为动作,
	  *         当实现类实现doeat方法时就可以监听到Person类对象eat(吃)这个动作
	  *
	  * @param e
	  */
	  void doeat(Event e);
	 
	  /**
	  * @Method: dorun
	  * @Description: 这个方法是用来监听Person对象run(跑)这个行为动作,
	  *         当实现类实现dorun方法时就可以监听到Person类对象run(跑)这个动作
	  *
	  * @param e
	  */
	  void dorun(Event e);
	 
	}
	 
	/**
	* @ClassName: Event(事件对象)
	* @Description:设计事件类,用来封装事件源
	*
	*/
	class Event {
	 
	  /**
	  * @Field: source
	  *     事件源(Person就是事件源)
	  */
	  private Person source;
	 
	  public Event() {
	 
	  }
	 
	  public Event(Person source) {
	    this.source = source;
	  }
	 
	  public Person getSource() {
	    return source;
	  }
	 
	  public void setSource(Person source) {
	    this.source = source;
	  }
}

PersonTest.class

public class PersonTest {
	 public static void main(String[] args) {
		    Person p = new Person();
		    //注册监听p对象行为的监听器
		    p.registerListener(new PersonListener() {
		      //监听p吃东西这个行为
		      public void doeat(Event e) {
		        Person p = e.getSource();
		        System.out.println(p + "在吃东西");
		      }
		      //监听p跑步这个行为
		      public void dorun(Event e) {
		        Person p = e.getSource();
		        System.out.println(p + "在跑步");
		      }
		    });
		    //p在吃东西
		    p.eat();
		    //p在跑步
		    p.run();
		  }

}

输出结果:

 

转自:

https://www.jb51.net/article/92036.htm

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值