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
  • 相关阅读:
    CDOJ 92 – Journey 【LCA】
    LCA-Tarjan算法
    【模板】无向图的割顶
    Codeforces 190E
    TwoSAT算法模板
    【转】STL之二分查找 (Binary search in STL)
    【转】数论模板
    【转】计算几何模板
    【转】string常用函数
    Codeforces 245G Suggested Friends
  • 原文地址:https://www.cnblogs.com/zchok/p/11805328.html
Copyright © 2011-2022 走看看