有两种实现
其中一种是Filter之间没有联系,全部Filter都存放在FilterChain中,由FilterChain来有序或无序地把把所有Filter调用一遍。没有用到链表这种数据结构。示例如下:
Java代码 收藏代码
package com.ljn.filter.custom;
import java.util.ArrayList;
import java.util.List;
/**
* 由FilterManager组织FilterChain,在FilterChain里面的filter顺序执行,
* 各Filter之间没有交互
*/
public class InterceptingFilterManager {
interface Filter {
void execute(String request, String response);
}
static class AuthenticationFilter implements Filter {
@Override
public void execute(String request, String response) {
System.out.println("AuthenticationFilter");
}
}
static class DebugFilter implements Filter {
@Override
public void execute(String request, String response) {
System.out.println("DebugFilter");
}
}
static class Target {
public void execute(String request, String response) {
System.out.println("Target");
}
}
static class FilterChain {
private List
private Target target;
public void addFilter(Filter filter) {
filters.add(filter);
}
//顺序执行,各filter之间没有直接联系
public void execute(String request, String response) {
for (Filter filter : filters) {
filter.execute(request, response);
}
target.execute(request, response);
}
public void setTarget(Target target) {
this.target = target;
}
}
public static void main(String[] args) throws Exception {
Target target = new Target();
Filter debugFilter = new DebugFilter();
Filter authenticationFilter = new AuthenticationFilter();
FilterChain chain = new FilterChain();
chain.addFilter(authenticationFilter);
chain.addFilter(debugFilter);
chain.setTarget(target);
String req = null;
String res = null;
chain.execute(req, res);
}
}
另一种是一个Filter“持有”下一个Filter,下一个Filter的调用由上一个Filter决定。这其中就用到了链表这种数据结构。
Java代码 收藏代码
package com.ljn.filter.custom;
/**
* 结合装饰模式,每个filter完成自己的处理后,显式调用下一个filter
*/
public class InterceptingFilterDecorator {
interface Filter {
void execute(String request, String response);
}
static class AuthenticationFilter implements Filter {
private Filter next;
public AuthenticationFilter(Filter next) {
this.next = next;
}
@Override
public void execute(String request, String response) {
System.out.println("AuthenticationFilter");
next.execute(request, response);
}
}
static class DebugFilter implements Filter {
private Filter next;
public DebugFilter(Filter next) {
this.next = next;
}
@Override
public void execute(String request, String response) {
System.out.println("DebugFilter");
next.execute(request, response);
}
}
static class Target implements Filter {
@SuppressWarnings("unused")
private Filter next;
public Target() {
this(null);
}
public Target(Filter next) {
this.next = next;
}
@Override
public void execute(String request, String response) {
System.out.println("Target");
// next.execute(request, response); //last one, no need to call next
}
}
public static void main(String[] args) throws Exception {
Filter processor = new AuthenticationFilter(
new DebugFilter(
new Target()));
String req = null;
String res = null;
processor.execute(req, res);
}
}