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

事件监听器原理——事件对象、事件监听器、事件源

时间:2015-06-19 18:17:25      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

package cn.my.demo;

//设计一个监听器
public class Demo2 {
    public static void main(String[] args) {
        Person p=new Person(1001,"张三");
        p.refisterListener(new PersonListener() {            
            public void dorun(Event e) {
                Person p=e.getSource();
                System.out.println("Who is in front of people to have a meal, that is "+p.getName());
            }
            
            public void doeat(Event e) {
                Person p=e.getSource();
                System.out.println("Who in the previous run, that is "+p.getName());
            }
        });
        
        p.eat();
        p.run();
    }
}
//观察者设计模式
class Person{    
    private Integer id ;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public Person(Integer id ,String name)
    {
        this.id=id;
        this.name=name;
    }
    //这个就是一个事件源
    private PersonListener listener;
    public void eat(){
        if(listener!=null){
            listener.doeat(new Event(this));
        }
        
        System.out.println("this is eat!");
    }
    public void run(){
        if(listener!=null){
            listener.dorun(new Event(this));
        }
        
        System.out.println("this is run!");
    }
    public void refisterListener(PersonListener listener){
        this.listener=listener;
    }
}

//事件监听器
interface PersonListener{
    public void doeat(Event e);
    public void dorun(Event e);
}

//这个是事件对象
class Event{
    //事件对象   需要封装事件源对象
    private Person source;

    public Person getSource() {
        return source;
    }
    public Event(Person source) {
        super();
        this.source = source;
    }
    public Event() {
        super();
    }
    public void setSource(Person source) {
        this.source = source;
    }
}

 

事件监听器原理——事件对象、事件监听器、事件源

标签:

原文地址:http://www.cnblogs.com/wucaifang/p/4589359.html

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