Java事件监听处理
一.简易事件实现
1.定义事件拦截器上下文
package com.zzc.design.intercept;
import java.util.Map;
public class InterceptContext {
/**
* 方法ID,需要保持唯一性
*/
private String methodId;
/**
* 参数或者其他的
*/
private Map<String, Object> params;
public String getMethodId() {
return methodId;
}
public void setMethodId(String methodId) {
this.methodId = methodId;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}
2.定义事件拦截接口
package com.zzc.design.intercept;
import java.util.Map;
public class InterceptContext {
/**
* 方法ID,需要保持唯一性
*/
private String methodId;
/**
* 参数或者其他的
*/
private Map<String, Object> params;
public String getMethodId() {
return methodId;
}
public void setMethodId(String methodId) {
this.methodId = methodId;
}
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}
3.定义事件管理器
package com.zzc.design.intercept;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class InterceptManager {
private static final Map<String, List<Interceptor>> interceptorManager = new HashMap<>();
public static List<Interceptor> getIntercept(String type) {
List<Interceptor> interceptors = interceptorManager.get(type);
if (interceptors == null) {
interceptors = new LinkedList<>();
interceptorManager.put(type, interceptors);
}
return interceptors;
}
public static void addIntercept(String type, Interceptor interceptor) {
getIntercept(type).add(interceptor);
}
}
4.使用
(1)实现事件拦截器
package com.zzc.design.intercept.demo;
import com.zzc.design.intercept.InterceptContext;
import com.zzc.design.intercept.InterceptManager;
import com.zzc.design.intercept.Interceptor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EventService implements Interceptor {
public final static String TYPE = "EVENT_TEST";
public EventService() {
InterceptManager.addIntercept(TYPE, this);
}
@Override
public void intercept(InterceptContext ctx) {
log.info("run intercept. methodId:{}", ctx.getMethodId());//so something
}
}
(2)调用者使用
package com.zzc.design.intercept.demo;
import com.zzc.design.intercept.InterceptContext;
import com.zzc.design.intercept.InterceptManager;
import com.zzc.design.intercept.Interceptor;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
EventService eventService = new EventService();
List<Interceptor> intercept = InterceptManager.getIntercept(EventService.TYPE);
for (Interceptor interceptor : intercept) {
InterceptContext ctx = new InterceptContext();
ctx.setMethodId("1111111111");
interceptor.intercept(ctx);
}
}
}
5.适用场景
- 以上时同步执行
- 代码解耦:流程处理一个阶段之后,发布事件给拦截器统一处理
- 异步执行:可以在Interceptor.intercept()实现异步执行
二.事件实现
TODO