文章目录
- 监听器模型
- 案例实现
- `DeveloperListener`
- `Developer`
- `Event`
- `DeveloperListenerImpl`
- 测试
监听器就是监听事件源是否发生了某一个事件,当发生指定监听的事件时事件源会向已注册的监听器发送消息对象。监听器可以获得事件对象进行相关操作。
监听器模型
- 事件源: 发生事件的对象
- 消息:触发监听的某一个事件
- 监听器:监听发生的某个事件进行业务处理
案例实现
在开发者进行开发和学习之前进行监听处理业务逻辑。
DeveloperListener
package demo.listener;
/**
* 监听器接口
* dingwen
* 2021/5/30 14:35
**/
public interface DeveloperListener {
/**
* 工作
*
* @param event 事件
*/
void work(Event event);
/**
* 研究
*
* @param event 事件
*/
void study(Event event);
}
Developer
package demo.listener;
import java.util.Optional;
import java.util.function.Supplier;
/**
* 开发者类
* dingwen
* 2021/5/30 14:34
**/
public class Developer {
private DeveloperListener developerListener;
/**
* 注册监听器
*
* @param 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;
/**
* 事件对象
* dingwen
* 2021/5/30 14:32
**/
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;
/**
* developer listener impl
* dingwen
* 2021/5/30 14:38
**/
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;
/**
* 测试
* dingwen
* 2021/5/30 14:57
**/
public class ListenerTest {
public static void main(String[] args) {
Developer developer = new Developer();
developer.registerListener(new DeveloperListenerImpl());
developer.study();
developer.work();
}
}