zoukankan      html  css  js  c++  java
  • 事件监听器原理——事件对象、事件监听器、事件源

    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;
        }
    }
  • 相关阅读:
    小程序实现无限瀑布流
    Vue H5 项目模板
    Taro使用mobx做国际化小程序
    一次国际化记录以及平铺JSON数据
    Promise(interesting)
    返回状态码
    CSS属性兼容写法
    在DOM加载之前insertScript
    关于吸烟
    前端优化措施
  • 原文地址:https://www.cnblogs.com/wucaifang/p/4589359.html
Copyright © 2011-2022 走看看