/** * 责任链模式:最形象的例子就是过滤器,一个字符串,经过一连串的过滤器,最后得到想要的字符串,例如,过滤HTMl标签,过滤敏感字符,过滤特殊字符 * 模式特点: 一个过滤器接口,多个实现类,其中一个实现类叫过滤器链,它里面有个集合存所有的过滤器,执行过滤时,就是从集合中拿出一个个过滤器来执行 * 相当于遍历,但跟遍历的表现形式不一样: * * * */ //定义过滤器链 public class FilterChain implements IFilter{ private List<IFilter> list=new ArrayList<>();//存储过滤器 private int index;//过滤器集合的执行索引 //注册过滤器 public void addFilter(IFilter filter){ list.add(filter); } //过滤方法 @Override public void filter(Request req, Response resp, FilterChain chain) { //当执行完所有的过滤器后就停止 if(index>=list.size()){ return; } //取出其中一个过滤器 IFilter filter = list.get(index); index++;//索引指向下一个过滤器的索引 //执行过滤器的过滤方法,这里传一个this对象作为参数,是为了在filter过滤器中还能再次调用chain.filter方法 //这样的话,每次进来这个方法,index索引就可以指向下个过滤器,因此相当于遍历集合了 filter.filter(req,resp,this); } } public interface IFilter { void filter(Request req,Response resp,FilterChain chain); } //a标签过滤器 public class AtagFilter implements IFilter { @Override public void filter(Request req, Response resp, FilterChain chain) { String reqParam = req.getReqParam(); reqParam=reqParam.replace("<a>",""); String replace = reqParam.replace("</a>", ""); req.setReqParam(replace); resp.setResponseStr(replace); chain.filter(req,resp,chain); } } //敏感字符过滤器 public class SensitiveFilter implements IFilter { @Override public void filter(Request req, Response resp, FilterChain chain) { String reqParam = req.getReqParam(); reqParam = reqParam.replace("脏话", ""); req.setReqParam(reqParam); resp.setResponseStr(reqParam); chain.filter(req,resp,chain); } } //特殊字符过滤器 public class SpecialCharFilter implements IFilter { @Override public void filter(Request req, Response resp, FilterChain chain) { String reqParam = req.getReqParam(); reqParam=reqParam.replace("#",""); String replace = reqParam.replace("$", ""); req.setReqParam(replace); resp.setResponseStr(replace); chain.filter(req,resp,chain); } } //请求对象 public class Request { //请求参数 private String reqParam; public String getReqParam() { return reqParam; } public void setReqParam(String reqParam) { this.reqParam = reqParam; } } //返回对象 public class Response { private String responseStr; public String getResponseStr() { return responseStr; } public void setResponseStr(String responseStr) { this.responseStr = responseStr; } } public class Test { public static void main(String[] args) { Request request = new Request();//创建请求对象 request.setReqParam("$<a>www.baidu</a> 脏话#"); Response response = new Response();//创建响应对象 FilterChain filterChain = new FilterChain();//创建责任链对象 filterChain.addFilter(new AtagFilter());//注册a标签过滤器 filterChain.addFilter(new SensitiveFilter());//注册敏感字符过滤器 filterChain.addFilter(new SpecialCharFilter());//注册特殊字符过滤器 filterChain.filter(request,response,filterChain);//调用过滤方法 //打印返回值,因为上面filter方法传入的参数是对象,引用类型,所以在过滤器中对该对象的改变会改变原对象 System.out.println(response.getResponseStr()); } }