一、我的理解
这个模式感觉跟Servlet中的过滤器类似,它让请求在被处理前可以先被定义好的过滤器使用并处理,有点类似AOP编程的意思。
二、实现方式
定义一个过滤器链和一个过滤器管理类,当请求到达时,先传递给管理类,管理类调用过滤器链过滤请求,并依次向下传递请求,当执行完最后一个过滤器时,再交给请求的目标处理类处理。
三、实例
Java实例
Filter接口:定义过滤器统一对外处理的接口函数
package com.study.dp.interceptingfilter;
public interface Filter {
public void execute(String request);
}
AuthenticationFilter类:实际的过滤器之一
package com.study.dp.interceptingfilter;
public class AuthenticationFilter implements Filter {
@Override
public void execute(String request) {
System.out.println("Authenticating request: "+request);
}
}
DebugFilter类:实际的过滤器之二
package com.study.dp.interceptingfilter;
public class DebugFilter implements Filter {
@Override
public void execute(String request) {
System.out.println("Request log: "+request);
}
}
FilterChain类:过滤器链
package com.study.dp.interceptingfilter;
import java.util.ArrayList;
import java.util.List;
public class FilterChain {
private List<Filter> filters = new ArrayList<>();
private Target target;
public void addFilter(Filter filter) {
filters.add(filter);
}
public void execute(String request) {
for(Filter filter:filters) {
filter.execute(request);
}
target.execute(request);
}
public void setTarget(Target target) {
this.target = target;
}
}
FilterManager类:过滤器管理类
package com.study.dp.interceptingfilter;
public class FilterManager {
FilterChain filterChain;
public FilterManager(Target target) {
filterChain = new FilterChain();
filterChain.setTarget(target);
}
public void setFilter(Filter filter) {
filterChain.addFilter(filter);
}
public void filterRequest(String request) {
filterChain.execute(request);
}
}
Target类:请求的实际处理类
package com.study.dp.interceptingfilter;
public class Target {
public void execute(String request) {
System.out.println("Executing request: "+request);
}
}
Client类:客户端程序
package com.study.dp.interceptingfilter;
public class Client {
FilterManager filterManager;
public void setFilterManager(FilterManager filterManager) {
this.filterManager = filterManager;
}
public void sendRequest(String request) {
filterManager.filterRequest(request);
}
}
Demo类:测试程序
package com.study.dp.interceptingfilter;
public class Demo {
public static void main(String[] args) {
FilterManager filterManager = new FilterManager(new Target());
filterManager.setFilter(new AuthenticationFilter());
filterManager.setFilter(new DebugFilter());
Client client = new Client();
client.setFilterManager(filterManager);
client.sendRequest("HOME");
}
}
四、应用场景