攔截過濾器模式(Intercepting Filter Pattern)用于對應(yīng)用程序的請求或響應(yīng)做一些預(yù)處理/后處理。定義過濾器,并在把請求傳給實際目標應(yīng)用程序之前應(yīng)用在請求上。過濾器可以做認證/授權(quán)/記錄日志,或者跟蹤請求,然后把請求傳給相應(yīng)的處理程序。以下是這種設(shè)計模式的實體。
我們將創(chuàng)建 FilterChain、FilterManager、Target、Client 作為表示實體的各種對象。AuthenticationFilter 和 DebugFilter 表示實體過濾器。
InterceptingFilterDemo,我們的演示類使用 Client 來演示攔截過濾器設(shè)計模式。
創(chuàng)建過濾器接口 Filter。
Filter.java
public interface Filter {
public void execute(String request);
}
創(chuàng)建實體過濾器。
AuthenticationFilter.java
public class AuthenticationFilter implements Filter {
public void execute(String request){
System.out.println("Authenticating request: " + request);
}
}
DebugFilter.java
public class DebugFilter implements Filter {
public void execute(String request){
System.out.println("request log: " + request);
}
}
創(chuàng)建 Target。
Target.java
public class Target {
public void execute(String request){
System.out.println("Executing request: " + request);
}
}
創(chuàng)建過濾器鏈。
FilterChain.java
import java.util.ArrayList;
import java.util.List;
public class FilterChain {
private List 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;
}
}
創(chuàng)建過濾管理器。
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);
}
}
創(chuàng)建客戶端 Client。
Client.java
public class Client {
FilterManager filterManager;
public void setFilterManager(FilterManager filterManager){
this.filterManager = filterManager;
}
public void sendRequest(String request){
filterManager.filterRequest(request);
}
}
使用 Client 來演示攔截過濾器設(shè)計模式。
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");
}
}
驗證輸出。
Authenticating request: HOME
request log: HOME
Executing request: HOME
更多建議: