📅  最后修改于: 2023-12-03 15:28:08.749000             🧑  作者: Mango
拦截过滤器模式(Interceptor Filter Pattern)是一种使用过滤器链来对请求进行预处理和过滤的设计模式。它可以在不修改目标对象的前提下,通过对请求进行过滤和预处理来达到不同的目的,比如安全验证、日志记录、性能监视等。
拦截过滤器模式主要由以下几个组件组成:
下面是一个典型的拦截过滤器模式的 UML 图:
拦截过滤器模式可以应用于多个场景,比如:
下面是一个简单的拦截过滤器模式的实现示例。
首先是 Filter 接口的定义:
public interface Filter {
void doFilter(Request request, Response response, FilterChain filterChain);
}
接下来是目标对象类 Target 的定义:
public class Target {
public void execute(Request request, Response response) {
// 执行目标操作
}
}
然后是 Filter Chain 的实现:
public class FilterChain {
private List<Filter> filters = new ArrayList<>();
public void addFilter(Filter filter) {
filters.add(filter);
}
public void doFilter(Request request, Response response) {
Iterator<Filter> iterator = filters.iterator();
// 依次执行过滤器
while (iterator.hasNext()) {
Filter filter = iterator.next();
filter.doFilter(request, response, this);
}
// 执行目标操作
new Target().execute(request, response);
}
}
最后是 Filter Impl 的实现:
public class LoggingFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain filterChain) {
// 执行日志记录操作
System.out.println("[Logging Filter] Logging Request: " + request.getMessage());
// 继续执行后续过滤器
filterChain.doFilter(request, response);
}
}
完整代码如下:
public class Client {
public static void main(String[] args) {
Request request = new Request("Hello World");
Response response = new Response();
FilterChain filterChain = new FilterChain();
filterChain.addFilter(new LoggingFilter());
// 执行过滤器链
filterChain.doFilter(request, response);
}
}
class Request {
private String message;
public Request(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
class Response {
// 空实现
}
interface Filter {
void doFilter(Request request, Response response, FilterChain filterChain);
}
class FilterChain {
private List<Filter> filters = new ArrayList<>();
public void addFilter(Filter filter) {
filters.add(filter);
}
public void doFilter(Request request, Response response) {
Iterator<Filter> iterator = filters.iterator();
// 依次执行过滤器
while (iterator.hasNext()) {
Filter filter = iterator.next();
filter.doFilter(request, response, this);
}
// 执行目标操作
new Target().execute(request, response);
}
}
class Target {
public void execute(Request request, Response response) {
// 执行目标操作
}
}
class LoggingFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain filterChain) {
// 执行日志记录操作
System.out.println("[Logging Filter] Logging Request: " + request.getMessage());
// 继续执行后续过滤器
filterChain.doFilter(request, response);
}
}
当我们运行客户端程序时,可以看到日志成功记录下来:
[Logging Filter] Logging Request: Hello World