监听模式
事件模型实现了监听模式,监听模式简单来说就是 事件源经过事件的封装传给监听器,当事件源触发事件后,监听器接收到事件对象可以回调事件的方法。
参与的角色
事件模型有三种角色参与,分别是:事件源、事件、事件监听器。
事件
事件继承自 java.util.EventObject 类,封装了事件源对象及跟事件相关的信息,代码可以说是很简单了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class EventObject implements java.io.Serializable { /** * 事件源 */ protected transient Object source; public EventObject(Object source) { if (source == null ) throw new IllegalArgumentException( "null source" ); this .source = source; } public Object getSource() { return source; } public String toString() { return getClass().getName() + "[source=" + source + "]" ; } } |
事件源
事件源是事件发生的地方,由于事件源的某项属性或状态发生了改变,
例如鼠标点击事件。
事件监听器
事件监听器实现 java.util.EventListener 接口,注册在事件源上,当事件源的属性或状态改变时,取得相应的监听器调用其内部的回调方法。最简单的代码,没有之一。
1 2 3 |
package java.util; public interface EventListener { } |
事件、事件源、监听器之间的关系
首先产生一个事件源(EventSource),然后事件(EventObject)封装事件源信息和事件信息,事件发生,事件源注册监听器,通知监听器,监听器处理事件。
举个粒子
事件对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class EventObject implements java.io.Serializable { /** * 事件源 */ protected transient Object source; public EventObject(Object source) { if (source == null ) throw new IllegalArgumentException( "null source" ); this .source = source; } public Object getSource() { return source; } public String toString() { return getClass().getName() + "[source=" + source + "]" ; } } |
事件对象Event继承EventObject,封装了事件源
1 2 3 4 5 6 |
import java.util.EventObject; public class Event extends EventObject { public Event(Object source) { super (source); } } |
事件源,事件源注册了事件监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.HashSet; import java.util.Set; public class Source { private String name; public void setName(String name) { this .name = name; } public String getName() { return name; } private final Set<Listener> listenerSet = new HashSet<>(); public void registerEventListener(Listener eventListener) { if (eventListener != null ) { listenerSet.add(eventListener); } } public void handle() { for (Listener eventListener : listenerSet) { Event event = new Event( this ); eventListener.callback(event); } } } |
事件监听器
1 2 3 4 |
import java.util.EventListener; public interface Listener extends EventListener { void callback(Event e); } |
测试
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Test { public static void main(String[] args) { Source source = new Source(); source.setName( "鼠标点击" ); System.out.println(source.getName()); source.registerEventListener((event) -> { //这里是处理逻辑 System.out.println( "鼠标事件回调被执行了---" ); System.out.println( "当前线程名称:" +Thread.currentThread().getName()); }); source.handle(); } } |
执行结果
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
原文链接:https://blog.csdn.net/Strange_boy/article/details/123530896