一、前言
监听器就是监听事件源是否发生了某一个事件,当发生指定监听的事件时事件源会向已注册的监听器发送消息对象。监听器可以获得事件对象进行相关操作。
二、监听器模型
- 事件源: 发生事件的对象
- 消息:触发监听的某一个事件
- 监听器:监听发生的某个事件进行业务处理
三、案例实现
在开发者进行开发和学习之前进行监听处理业务逻辑。
DeveloperListener
package demo.listener;
public interface DeveloperListener {
void work(Event event);
void study(Event event);
}
Developer
package demo.listener;
import java.util.Optional;
import java.util.function.Supplier;
public class Developer {
private DeveloperListener developerListener;
public void registerListener(DeveloperListener developerListener) {
this.developerListener = developerListener;
}
public void work() {
if (developerListener != null) {
this.developerListener.work(new Event(this));
}
System.out.println("developer work");
}
public void study(){
if (developerListener != null){
this.developerListener.study(new Event(this));
System.out.println("developer study");
}
}
}
Event
package demo.listener;
public class Event {
private Developer developer;
public Event(Developer developer) {
this.developer = developer;
}
public Event() {
}
public Developer getDeveloper() {
return developer;
}
public void setDeveloper(Developer developer) {
this.developer = developer;
}
}
DeveloperListenerImpl
package demo.listener;
public class DeveloperListenerImpl implements DeveloperListener {
@Override
public void work(Event event) {
Developer developer = event.getDeveloper();
System.out.println("work developer impl listener");
}
@Override
public void study(Event event) {
Developer developer = event.getDeveloper();
System.out.println("study developer impl listener");
}
}
四、测试
package demo.listener;
public class ListenerTest {
public static void main(String[] args) {
Developer developer = new Developer();
developer.registerListener(new DeveloperListenerImpl());
developer.study();
developer.work();
}
}
到此这篇关于如何实现Java监听器详解的文章就介绍到这了,更多相关Java监听器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!