首页 > 其他 > 详细

简单的拦截器模式实现,赋类图

时间:2021-09-02 15:43:21      阅读:12      评论:0      收藏:0      [点我收藏+]

 拦截器模式,是用巧妙的递归实现拦截功能的。

  类图结构如:技术分享图片

代码实现:

接口:interceptor:


import java.util.List;

public interface Interceptor {
public List<String> interceptor(TargetInterceptor targetInterceptor);
}

接口Target:
public interface Target {
public List<String> excute(int count);
}


实现一下
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TargetInterceptor {
private List<Interceptor> interceptorList = new ArrayList<Interceptor>();
private Iterator<Interceptor> interceptors;
private int count;
private Target target;

public List<String> invoke(){
if(interceptors.hasNext()){
Interceptor interceptor = interceptors.next();
return interceptor.interceptor(this);
}
return target.excute(count);
}

public void addInterceptor(Interceptor interceptor){
interceptorList.add(interceptor);
interceptors = interceptorList.iterator();
}

public void setCount(int count) {
this.count = count;
}

public void setTarget(Target target) {
this.target = target;
}

public int getCount() {
return count;
}

public Target getTarget() {
return target;
}
}
写个日志试试:
import java.util.List;

public class LogInterceptor implements Interceptor{
@Override
public List<String> interceptor(TargetInterceptor targetInterceptor) {
System.out.println("操作在执行之前");
List<String> data = targetInterceptor.invoke();
System.out.println("操作在执行之后");
return data;
}
}
调用;
import java.util.List;

public class StartMain {
public static void main(String[] args) {
TargetInterceptor targetInvocation = new TargetInterceptor();
targetInvocation.addInterceptor(new LogInterceptor());
targetInvocation.setCount(20);
targetInvocation.setTarget(new DataCountTarget());
List<String> data = targetInvocation.invoke();
for (String item: data) {
System.out.println(item);
}
}
}
输出:

技术分享图片

 


 

简单的拦截器模式实现,赋类图

原文:https://www.cnblogs.com/Howe7785/p/15217129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!