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
  • 相关阅读:
    如何安装ArchLinux
    状态模式
    iOS设备的越狱方法
    浅析Windows安全相关的一些概念
    项目做成jar包
    JavaScript包装对象
    node.js系列笔记之node.js初识《一》
    使用Reactive Extensions(Rx),对短时间内多次发生的事件限流
    in和exists哪个效率高本人测试证明
    Asp.net MVC使用Filter解除Session, Cookie等依赖
  • 原文地址:https://www.cnblogs.com/zchok/p/11805328.html
Copyright © 2011-2022 走看看