写了一小段关于过滤器、过滤器链的 Toy Code
一、过滤器接口
public interface Filter {
public void doFilter(Invocation invocation, FilterChain chain);
}
过滤器实现一
public class FirstFilter implements Filter {
public void doFilter(Invocation invocation, FilterChain chain) {
System.out.println("before: args size=" + invocation.getArgs().length);
chain.doFilter(invocation);
System.out.println("after: args size=" + invocation.getArgs().length); //注释掉?
}
}
过滤器实现二
public class SecondFilter implements Filter {
public void doFilter(Invocation invocation, FilterChain chain) {
System.out.println("before: arg=" + Arrays.asList(invocation.getArgs()));
chain.doFilter(invocation);
System.out.println("after: arg=" + Arrays.asList(invocation.getArgs()));// 注释掉?
}
}
二、过滤器链接口
public interface FilterChain {
public FilterChain addFilter(Filter filter);
public void doFilter(Invocation invocation);
}
过滤器链实现
public class DefaultFilterChain implements FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
private int index = 0;
public FilterChain addFilter(Filter filter) {
filters.add(filter);
return this;
}
public void doFilter(Invocation invocation) {
if (filters.isEmpty())
return;
if (index == filters.size()) {
// 一次过滤器链调用结束,复位index.不复位会怎样?
index = 0;
return;
}
filters.get(index++).doFilter(invocation, this);
}
}
三、服务类
public class Service {
public void say(String name) {
System.out.println("hello " + name);
}
}
四、辅助类
public class Invocation {
private Object target;
private Method method;
private Object[] args;
public Invocation(Object target, Method method, Object[] args) {
super();
this.target = target;
this.method = method;
this.args = args;
}
public Object invoke() throws Exception {
return method.invoke(target, args);
}
//... getter & setter
}
五、调用场景类
public class Context {
private FilterChain chain;
private Invocation invocation;
public Context(FilterChain chain, Invocation invocation) {
super();
this.chain = chain;
this.invocation = invocation;
}
public Object invoke() throws Exception {
chain.doFilter(invocation);
return invocation.invoke();
}
public static void main(String[] args) throws Exception {
FilterChain chain = new DefaultFilterChain().addFilter(new FirstFilter()).addFilter(new SecondFilter());
Invocation invocation = new Invocation(new Service(), Service.class.getMethod("say", String.class),
new Object[] { "jack" });
Context context = new Context(chain, invocation);
context.invoke(); //循环调用invoke会怎样?
}
}
运行结果
before: args size=1
before: arg=[jack]
after: arg=[jack]
after: args size=1
hello jack
六、UML类图
Web工程里面web.xml配置的Filter实现是不是也是这个道理?
是的!