1、AWT中的监听器
在JAVA的GUI编程中,大量使用了事件监听器。下面的小DEMO创建了一个小窗口f,并给f加了一个监听器,在监听器中覆写了windowClosing方法,监听f的关闭事件。当点击关闭时,触发事件 –> 产生事件对象 –> 调用监听器中对应方法。
public class FrameDemo { public static void main(String[] args) { //Frame f:事件源 Frame f = new Frame("小窗口"); f.setSize(200, 200); f.setVisible(true); //注册监听器 f.addWindowListener(new MyWindowListener()); } } //MyWindowListener:监听器 class MyWindowListener extends WindowAdapter{ //WindowEvent e:事件对象,引用着事件源对象 public void windowClosing(WindowEvent e) { Frame f = (Frame)e.getSource(); f.dispose(); } }
实际上,监听器是观察者设计模式的一种典型应用。
2、观察者设计模式
① 几个概念(☆)
- 事件源:触发事件的对象。【例子中的Frame f 】
- 事件对象:封装了事件源。【例子中的WindowEvent e】
- 事件监听器:一般是一个接口,由使用者来实现。【new MyWindowListener()】
② 一个观察者模式的demo
描述:有个Student类,有study、sleep等行为,设计一个监听器,对Student类的两个行为进行监听。
事件源:Student
事件对象:StudentEvent
事件监听器:StudentListener
---------------------- 先看看DEMO(和上面AWT的DEMO很像吧) ---------------------- public class Demo { public static void main(String[] args) { Student s = new Student("Flyne"); //给事件源s注册一个事件监听器 s.addStudentListener(new StudentListener() { public void postStudy(StudentEvent e) { Student s1 = (Student)e.getSource(); System.out.println(s1.getName()+",学完了放松放松吧。"); } public void preSleep(StudentEvent e) { Student s1 = (Student)e.getSource(); System.out.println(s1.getName()+",睡觉前喝杯牛奶吧!"); } }); //事件发生 --> 产生事件对象 --> 调用监听器中的相应方法 s.study(); s.sleep(); } } -------------------------------- 看看这是如何实现的 -------------------------------- public interface StudentListener { //对study事件进行监听,该事件结束后调用 void postStudy(StudentEvent e); //对sleep时间进行监听,该事件开始前调用 void preSleep(StudentEvent e); } public class StudentEvent { //在事件中封装了事件源 private Object source; public StudentEvent(Object source){ this.source = source; } public Object getSource(){ return source; } public Student getStudent(){ return (Student)source; } } public class Student { private String name; //在事件源中保持了监听器的引用(☆) private StudentListener listener; public Student(String name){ this.name = name; } public void study(){ System.out.println(name+"开始学习"); if(listener!=null){//如果注册了该监听器 listener.postStudy(new StudentEvent(this)); } } public void sleep(){ if(listener!=null){//如果注册了该监听器 listener.preSleep(new StudentEvent(this)); } System.out.println(name+"开始睡觉"); } //在事件源中要有注册监听器的方法: public void addStudentListener(StudentListener listener){ this.listener = listener; } public String getName() { return name; } }
3、Servlet规范中八个监听器(3组)
1)监听context、session、request对象创建和销毁的监听器
- ServletContextListener(☆)
- HttpSessionListener
- ServletRequestListener
2)监听ServletContext、HttpSession、ServletRequest中属性变化的监听器,如setAttribute、removeAttribute
- ServletContextAttributeListener
- HttpSessionAttributeListener
- ServletRequestAttributeListener
3)感知型监听器,这种监听器不需要注册,都与会话有关
- HttpSessionBindingListener:感知自己被放到了HttpSession属性中
- HttpSessionActivationListener:感知自己何时随着HttpSession钝化或激活
- 本文固定链接: http://www.flyne.org/article/646
- 转载请注明: 东风化宇 2014年08月30日 于 Flyne 发表
thx