package cn.edu.hpu.responsibility; public interface Filter { /*你可以定义一系列规则来实现 这个Filter接口,在这个接口实现里面, 你可以把原来的字符串做任意的处理, 同时反馈给一个新的字符串*/ String doFilter(String str); }
package cn.edu.hpu.responsibility; public class HTMLFilter implements Filter { @Override public String doFilter(String str) { return null; } }
package cn.edu.hpu.responsibility; public class SesitiveFilter implements Filter { @Override public String doFilter(String str) { String r=str.replace("偷盗", "和谐") .replace("抢劫", "帮助"); return r; } }
package cn.edu.hpu.responsibility; public class MsgProcessor { private String msg; //把众多的过滤规则(不同的过滤器)整合在一起 Filter[] filters={new HTMLFilter(),new SesitiveFilter()}; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String process(){ String r=msg; //处理脚本语句和敏感字眼 for(Filter f:filters){ r=f.doFilter(r); } 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); String result=mp.process(); System.out.println(result); } }
请看下一片总结:http://blog.csdn.net/acmman/article/details/44673409
转载请注明出处:http://blog.csdn.net/acmman/article/details/44673311