事件监听器模式

事 件 监 听 器 模 式

 

  监听器将监听感兴趣的事件,一旦事件发生,便做出响应

 

其涉及到的三个组件:

  事件源(Event Source)

  事件监听器(Event Listener)

  事件对象(Event Object)

 

 

 

代码演示:

 

创建Event(事件类)

@Getter @Setter
public class Event {
    private String type;
}

 

创建EventListener(事件监听接口)

public interface EventListener {
    public  void  processEvent(Event event);
}

 

创建SingleClickEventListener(单击事件监听器)(实现了事件监听接口)

public class SingleClickEventListener implements EventListener {
    @Override
    public void processEvent(Event event) {
        if("singleclick".equals(event.getType())){
            System.out.println("单击被触发了");
        }
    }
}

 

创建DoubleClickEventListener(双击事件监听器)(实现了事件监听接口)

public class DoubleClickEventListener implements EventListener {
    @Override
    public void processEvent(Event event) {
        if("doubleclick".equals(event.getType())){
            System.out.println("双击被触发了");
        }
    }
}

 

 

创建EventSource (事件源)

public class EventSource {
    private List<EventListener> listenerList = new ArrayList<>();
    
    public void register(EventListener listener){
        listenerList.add(listener);
    }

    public void publishEvent(Event event){
        for (EventListener listener:listenerList){
            listener.processEvent(event);
        }
    }
}

 

 

=====================================================

此时我们创建Demo中的main方法进行测试

public class EventModeDemo {

    public static void main(String[] args) {
        EventSource eventSource = new EventSource();
        SingleClickEventListener singleClickEventListener = new SingleClickEventListener();
        DoubleClickEventListener doubleClickEventListener = new DoubleClickEventListener();
        
     Event event
= new Event();
     event.setType("doubleclick");
eventSource.register(singleClickEventListener); eventSource.register(doubleClickEventListener); eventSource.publishEvent(event); } }

 

运行结果:

=========================

双击被触发了

=========================

 

posted @ 2021-02-18 15:43  _kerry  阅读(208)  评论(0编辑  收藏  举报