package cn.edu.hpu.responsibility; import java.util.List; import java.util.ArrayList; public class FilterChain { List<Filter> filters=new ArrayList<Filter>(); //返回值是FilterChain只为了在Main中满足链条式的编程 public FilterChain addFilter(Filter f) { this.filters.add(f); return this; } }
public String doFilter(String str) { String r=str; for(Filter f:filters){ r=f.doFilter(r); } return r; }也就是:
package cn.edu.hpu.responsibility; import java.util.List; import java.util.ArrayList; public class FilterChain { List<Filter> filters=new ArrayList<Filter>(); //返回值是FilterChain只为了在Main中满足链条式的编程 public FilterChain addFilter(Filter f) { this.filters.add(f); return this; } public String doFilter(String str) { String r=str; for(Filter f:filters){ r=f.doFilter(r); } return r; } }
package cn.edu.hpu.responsibility; public class MsgProcessor { private String msg; //把众多的过滤规则(不同的过滤器)整合在一起 //Filter[] filters={new HTMLFilter(),new SesitiveFilter()}; FilterChain fc; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public FilterChain getFc() { return fc; } public void setFc(FilterChain fc) { this.fc = fc; } public String process(){ //处理脚本语句和敏感字眼 return fc.doFilter(msg); } }
package cn.edu.hpu.responsibility; public class Main { public static void main(String[] args) { String msg="大家好:),<script>,偷盗,抢劫,我们要把设计模式学好"; MsgProcessor mp=new MsgProcessor(); mp.setMsg(msg); FilterChain fc=new FilterChain(); fc.addFilter(new HTMLFilter()) .addFilter(new SesitiveFilter());//链条式写法 mp.setFc(fc); String result=mp.process(); System.out.println(result); } }运行结果:
package cn.edu.hpu.responsibility; public class FaceFilter implements Filter { @Override public String doFilter(String str) { //笑脸过滤器 String r=str.replace(":)", "^_^"); return r; } }
package cn.edu.hpu.responsibility; public class Main { public static void main(String[] args) { String msg="大家好:),<script>,偷盗,抢劫,我们要把设计模式学好"; MsgProcessor mp=new MsgProcessor(); mp.setMsg(msg); FilterChain fc=new FilterChain(); fc.addFilter(new HTMLFilter()) .addFilter(new SesitiveFilter());//链条式写法 FilterChain fc2=new FilterChain(); fc2.addFilter(new FaceFilter()); fc.addFilter(fc2); mp.setFc(fc); String result=mp.process(); System.out.println(result); } }测试结果:
package cn.edu.hpu.filter.web; public class Request { private String requestStr; public String getRequestStr() { return requestStr; } public void setRequestStr(String requestStr) { this.requestStr = requestStr; } }
package cn.edu.hpu.filter.web; public class Response { private String responseStr; public String getResponseStr() { return responseStr; } public void setResponseStr(String responseStr) { this.responseStr = responseStr; } }
下一篇总计继续:http://blog.csdn.net/acmman/article/details/44673483
转载请注明出处:http://blog.csdn.net/acmman/article/details/44673409