zoukankan      html  css  js  c++  java
  • 事件模型监听器EventObject

    参照 https://www.cnblogs.com/lichmama/p/8976092.html


    模型:

      事件Event、事件源Source、监听器Listener

      事件源注册监听器、事件传入事件源。事件发生,通知监听器,监听器处理

    demo:

      事件Event:

    public class Event {
    
        private Source source;
    
        public Event(Source source) {
            if(source == null)
                throw new IllegalArgumentException("null source");
            this.source = source;
        }
    
    
        public Source getSource() {
            return source;
        }
    }

      

      事件源Source:

    public class Source {
    
        private String name;
    
        public void setName(String name){
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        private Set<EventListener> listenerSet = new HashSet<>();
    
        public void registerEventListener(EventListener eventListener){
            if (eventListener != null){
                listenerSet.add(eventListener);
            }
        }
    
        public void handle(){
            for (EventListener eventListener : listenerSet) {
                ThreadPoolUtil.execute(()-> {
                        Event event = new Event(this);
                        eventListener.callback(event);
                });
            }
        }
    
    }

      监听器Listener

    public interface EventListener {
    
        void callback(Event e);
        
    }

      测试

    public class App {
    
        public static void main(String[] args) {
            Source source = new Source();
            source.setName("av");
    
            source.registerEventListener((event)->{
                    System.out.println("one....");
                    System.out.println(event.getSource().getName());
                    System.out.println(Thread.currentThread().getName());
            });
    
            source.registerEventListener((event)->{
                    System.out.println("two....");
                    System.out.println(event.getSource().getName());
                    System.out.println(Thread.currentThread().getName());
            });
    
            source.handle();
        }
    }

      结果:

    two....
    av
    pool-1-thread-1
    one....
    av
    pool-1-thread-2
  • 相关阅读:
    Linux sort -n 与 -g 排序对比
    shell中IF的用法介绍
    Firewalld 用法解析
    Centos7最小化安装后再安装图形界面
    PXE无人值守部署centos7.4操作系统
    kali之获取靶机的图片和看的url
    Kali的源得数字验证问题
    kali之Nmap (Network Mapper(网络映射器)
    kali之EtterCap学习
    Kali linux查看局域网内其他用户的输入信息
  • 原文地址:https://www.cnblogs.com/zchok/p/11805328.html
Copyright © 2011-2022 走看看