码迷,mamicode.com
首页 > 其他好文 > 详细

监听器和 利 用观察者设计模式设计一个程序

时间:2014-06-29 23:29:36      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:java   监听器   

一、监听器概念
    1、事件源:发生事件的对象。
    2、监听器:是一个接口,监听事件源上要发生的动作
    3、事件:事件对象一般是作为监听器方法的参数存在的,它封装了发生事件的对象

二、Servlet中提供的监听器(8个)
    八个监听器分类:
    2.1监听ServletContext、HttpSession、ServletRequest对象的创建和销毁的监听器。
        ServletContextListener:监听ServletContext对象的创建和销毁。
        
        HttpSessionListener:监听HttpSession对象的创建和销毁。
                    创建:第一次调用request.getSession()时。
                          销毁:1、主动调用invalidate()方法
                                2、超时
                                
        ServletRequestListener:监听ServletRequest对象的创建和销毁。
                    
    2.2监听ServletContext、HttpSession、ServletRequest对象中域变化(新来的,替换的,删除的)的监听器。
        ServletContextAttributeListener:
        HttpSessionAttributeListener:
        ServletRequestAttributeListener:
    2.3感知型监听器:谁实现了这些接口,谁就能感知自己被怎么着了。这种监听器不需要注册。
        HttpSessionActivationListener:感知自己何时随着HttpSession对象钝化和活化
        HttpSessionBindingListener:感知自己何时被HttpSession对象绑了(绑在域中)和解绑了。
        
    
    编写步骤:
        1、编写一个类实现某个监听器接口
        2、在web.xml中注册监听器
            <listener>
                <listener-class>cn.usst.listener.ServletContextDemoListener</listener-class>

            </listener>

三、观察者设计模式设计一个程序

//事件源
public class Student implements Serializable{
	private String name;
	private StudentListener listener;
	public Student(String name){//注入:通过构造方法
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void eat(){
		if(listener!=null){
			listener.preEat(new StudentEvent(this));
		}
		System.out.println("开始吃");
	}
	public void study(){
		if(listener!=null){
			listener.preStudy(new StudentEvent(this));
		}
		System.out.println("开始学");
	}
}

public class StudentEvent {
	private Object source;

	public StudentEvent(Object source){
		this.source = source;
	}
	public Object getSource() {//获取事件源
		return source;
	}	
}

public interface StudentListener {
	void preEat(StudentEvent e);//监听吃
	void preStudy(StudentEvent e);//监听学
}

测试用例:

public static void main(String[] args) {
		Student s = new Student("葛付以");
		
		//注册监听器
		s.addStudentListener(new StudentListener() {
			
			public void preStudy(StudentEvent e) {
				Student ss = (Student) e.getSource();
				System.out.println(ss.getName()+"喝杯奶吧");
			}
			
			public void preEat(StudentEvent e) {
				Student ss = (Student) e.getSource();
				System.out.println(ss.getName()+"慢慢吃");
			}
		});
		
		s.eat();
		s.study();
	}



监听器和 利 用观察者设计模式设计一个程序,布布扣,bubuko.com

监听器和 利 用观察者设计模式设计一个程序

标签:java   监听器   

原文地址:http://blog.csdn.net/ankeyuan/article/details/35597699

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!