java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java拦截过滤器

Java拦截过滤器模式 (Intercepting Filter )实现方法

作者:一名技术极客

拦截过滤器模式(Intercepting Filter Pattern)用于对应用程序的请求或响应做一些预处理/后处理,本文通过实例代码介绍Java拦截过滤器模式 (Intercepting Filter )的相关知识,感兴趣的朋友跟随小编一起看看吧

Java拦截过滤器模式

实现

范例

1. 创建过滤器接口 Filter

Filter.java

package com.demo.gof;
public interface Filter {
   public void execute(String request);
}

2. 创建实体过滤器

AuthenticationFilter.java

package com.demo.gof;
public class AuthenticationFilter implements Filter {
   public void execute(String request){
      System.out.println("Authenticating request: " + request);
   }
}

DebugFilter.java

package com.demo.gof;
public class DebugFilter implements Filter {
   public void execute(String request){
      System.out.println("request log: " + request);
   }
}

3. 创建 Target

Target.java

package com.demo.gof;
public class Target {
   public void execute(String request){
      System.out.println("Executing request: " + request);
   }
}

4. 创建过滤器链

FilterChain.java

package com.demo.gof;
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

package com.demo.gof;
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

Client.java

package com.demo.gof;
public class Client {
   FilterManager filterManager;
   public void setFilterManager(FilterManager filterManager){
      this.filterManager = filterManager;
   }
   public void sendRequest(String request){
      filterManager.filterRequest(request);
   }
}

7. 使用 Client 来演示拦截过滤器设计模式

FrontControllerPatternDemo.java

package com.demo.gof;
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");
   }
}

编译运行以上 Java 范例,输出结果如下

$ javac -d . src/main/com.demo/gof/InterceptingFilterDemo.java
$ java  com.demo.gof.InterceptingFilterDemo
Authenticating request: HOME
request log: HOME
Executing request: HOME

到此这篇关于Java拦截过滤器模式 ( Intercepting Filter )的文章就介绍到这了,更多相关Java拦截过滤器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文