监听器将监听感兴趣的事件,一旦事件发生,便做出响应,有以下几个概念:
- 事件源(Event Source)
- 事件监听器(Event Listener)
- 事件对象(Event Object)
主要负责在事件源和事件监听器之间的信息传递
示例代码
package demo.pattern.eventmode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Event {
private String type;
}
package demo.pattern.eventmode;
public interface EventListener {
public void processEvent(Event event);
}
package demo.pattern.eventmode;
public class SingleClickEventListener implements EventListener {
@Override
public void processEvent(Event event) {
if("singleclick".equals(event.getType())){
System.out.println("单击被触发了");
}
}
}
package demo.pattern.eventmode;
public class DoubleClickEventListener implements EventListener {
@Override
public void processEvent(Event event) {
if("doubleclick".equals(event.getType())){
System.out.println("双击被触发了");
}
}
}
package demo.pattern.eventmode;
import java.util.ArrayList;
import java.util.List;
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); // 注册事件
}
}
}
package demo.pattern.eventmode;
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);
}
}
执行了之后只有doubleClickEventListener响应了事件。
回调函数
往组件注册自定义的方法以便组件在特定场景下调用
Spring的事件驱动模型
事件:ApplicatinEvent抽象类