• 事件模型监听器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
  • 相关阅读:
    View相关知识学习总结
    关于Android四大组件的学习总结
    Android开发框架--AndroidAnnotations(一)
    USACO 3.4
    hdu 2723
    hdu 2721
    hdu 2719
    hdu 1527
    hdu 1260
    hdu 2603
  • 原文地址:https://www.cnblogs.com/zchok/p/11805328.html
Copyright © 2020-2023  润新知