事件处理的三要素
监听器模式:事件源经过事件的封装传给事件监听器,当事件源触发事件后,监听器接收到事件对象可以回调事件的方法
从而我们要先定义一个事件源:
假如需求如下:
有一个校花级别的美女,她有很多追求者,她作为一个事件源,这些追求者作为监听器,因为监听器会对事件源的喜怒哀乐做出相关的反应。例如,校花心情不好了,监听器们会表现表现带她去看电影,吃东西,送花啥的等等;
先定义一个事件源类:
import java.util.ArrayList;
import java.util.List;
//事件源
public class Girl {
private String name;
//为追求者们建立一个容器
private List<EmotionListener> els = new ArrayList<EmotionListener>();
public Girl(String name){
this.name = name;
}
//女神添加追求者到自己的考虑范围
public void addEmotionListener(EmotionListener e){
els.add(e);
}
//女神从考虑范围内删除
public void removeEmotionListener(EmotionListener e){
els.remove(e);
}
//女神高兴的时候
//发出高兴这个状态,让追求者们知道
//即遍历追求者数组,让追求者们调用自己在女神高兴时要做的动作
public void happy(){
EmotionEvent e = new EmotionEvent(this);
for(EmotionListener em : els){
try {
em.happy(e);
} catch (EmotionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
校花的情绪类
也就是发情绪这个事件的对象
package com.ActionEvent;
//情绪 的事件对象
public class EmotionEvent {
/**
* @param args
*/
private Girl source;
public EmotionEvent(Girl source){
this.setSource(source);
}
public void setSource(Girl source) {
this.source = source;
}
public Girl getSource() {
return source;
}
}
创建追求者类
也就是负责监听女神心情的监听者们,由于每一个监听者对自己的女神做出的动作不同,从而定义为一个接口
package com.ActionEvent;
//boy 事件监听
public interface EmotionListener {
//e 监听的事件对象
public void happy(EmotionEvent e)throws EmotionException;
public void sad(EmotionEvent e)throws EmotionException;
}
一个简单的自定义异常类
package com.ActionEvent;
public class EmotionException extends Exception{
public EmotionException() {
super();
}
public EmotionException(String message, Throwable cause) {
super(message, cause);
}
public EmotionException(String message) {
super(message);
}
public EmotionException(Throwable cause) {
super(cause);
}
}
测试类:
package com.ActionEvent;
public class EmotionTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//构建校花女孩对象
Girl mr = new Girl("马蓉");
Girl sy = new Girl("宋雅");
EmotionListener bb = new EmotionListener(){
public void happy(EmotionEvent e)throws EmotionException{
Girl g = e.getSource();
if(g.getName().equals("马蓉")){
System.out.println("宝强送给校花"+e.getSource()+"一辆跑车!");
}
else{
System.out.println("宝强的礼物当年只送给前妻马蓉!");
}
}
public void sad(EmotionEvent e)throws EmotionException{
}
};
EmotionListener sz = new EmotionListener(){
public void happy(EmotionEvent e)throws EmotionException{
Girl g = e.getSource();
if(g.getName().equals("马蓉")){
System.out.println("宋哲给"+g+"一套房子!");
}
if(g.getName().equals("宋雅")){
System.out.println("宋哲给"+g+"一个棒棒糖!");
}
}
public void sad(EmotionEvent e)throws EmotionException{}
};
//女神加关注
mr.addEmotionListener(bb);
mr.addEmotionListener(sz);
sy.addEmotionListener(bb);
sy.addEmotionListener(sz);
//触发事件
System.out.println(mr.getName()+"触动了 happy 方法");
mr.happy();
System.out.println(sy.getName()+"触动了 happy 方法");
sy.happy();
}
}
输出结果