实例
我们将创建一个FilterChain,FilterManager,Target,Client作为代表我们实体的各种对象。AuthenticationFilter和DebugFilter代表具体的过滤器。
我们的演示类InterceptingFilterDemo将使用Client演示Intercepting过滤器设计模式。
第1步 - 创建过滤器接口。 Filter.java
public interface Filter {
public void execute(String request);
}
第2步 - 创建具体的过滤器。AuthenticationFilter.java,DebugFilter.java
public class AuthenticationFilter implements Filter {
public void execute(String request){
System.out.println("Authenticating request: " + request);
}
}
public class DebugFilter implements Filter {
public void execute(String request){
System.out.println("request log: " + request);
}
}
第3步 - 建立目标。Target.java
public class Target {
public void execute(String request){
System.out.println("Executing request: " + request);
}
}
步骤4 - 创建过滤链。FilterChain.java
import java.util.ArrayList;
import java.util.List;
public class FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
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;
}
}
第5步 创建过滤器管理器 。 FilterManager.java
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);
}
}
第6步创建客户端。Client.java
public class Client {
FilterManager filterManager;
public void setFilterManager(FilterManager filterManager){
this.filterManager = filterManager;
}
public void sendRequest(String request){
filterManager.filterRequest(request);
}
}
步骤7 - 使用客户端演示拦截过滤器设计模式。InterceptingFilterDemo.java
public class InterceptingFilterDemo {
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");
}
}
步骤8 - 验证输出。
Authenticating request: HOME
request log: HOME
Executing request: HOME