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

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

  类图结构如:简单的拦截器模式实现,赋类图

代码实现:

接口: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);
}
}
}
输出:

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

 


 

上一篇:MyBatis拦截器原理探究


下一篇:Spring filter interceptor controllerAdvice aspect controller调用顺序