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


    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;
        }
    }
  • 相关阅读:
    【Android】6.3 ProgressDialog
    【Android】6.2 AlertDialog(警告对话框)
    【Android】6.1 Toast(信息提示框)
    【Android】6.0 第6章 对话框--本章示例主界面
    【Android】5.8 滑动条(SeekBar)
    Storm Trident API
    Storm Trident状态
    Storm Trident详解
    Storm的并行度
    StormUI详解
  • 原文地址:https://www.cnblogs.com/wucaifang/p/4589359.html
Copyright © 2020-2023  润新知