一、目标
增加filterchain功能
二、代码
1.Filter.java
1 public interface Filter { 2 public String doFilter(String str); 3 }
2.FilterChain.java
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class FilterChain implements Filter { 5 6 private List<Filter> filters = new ArrayList<Filter>(); 7 8 public String doFilter(String str) { 9 for(Filter f : filters){ 10 str = f.doFilter(str); 11 } 12 return str; 13 } 14 15 //把函数的返回值设为FilterChain,返回this,就能方便链式编写代码 16 public FilterChain addFilter(Filter filter) { 17 filters.add(filter); 18 return this; 19 } 20 21 }
3.HTMLFilter.java
1 public class HTMLFilter implements Filter { 2 3 @Override 4 public String doFilter(String str) { 5 return str.replace(‘<‘, ‘[‘).replace(">", "]"); 6 } 7 8 }
4.SensitiveFilter.java
1 public class SensitiveFilter implements Filter { 2 3 @Override 4 public String doFilter(String str) { 5 return str.replace("敏感", "幸福"); 6 } 7 8 }
5.MsgProcessor.java
1 public class MsgProcessor { 2 3 //private List<Filter> filters = new ArrayList<Filter>(); 4 FilterChain filterChain; 5 private String msg; 6 7 public FilterChain getFilterChain() { 8 return filterChain; 9 } 10 11 public void setFilterChain(FilterChain filterChain) { 12 this.filterChain = filterChain; 13 } 14 15 16 public String getMsg() { 17 return msg; 18 } 19 20 public void setMsg(String msg) { 21 this.msg = msg; 22 } 23 24 public String process() { 25 return filterChain.doFilter(msg); 26 } 27 }
6.Test.java
1 public class Test { 2 3 @org.junit.Test 4 public void testFilter(){ 5 6 MsgProcessor processor = new MsgProcessor(); 7 8 String msg = "<html>敏感字眼</html>"; 9 processor.setMsg(msg); 10 11 FilterChain fc1 = new FilterChain(); 12 fc1.addFilter(new HTMLFilter()); 13 14 FilterChain fc2 = new FilterChain(); 15 fc2.addFilter(new SensitiveFilter()); 16 17 //由于FilterChain实现了Filter接口,所以FilterChain同时也是Filter,所以可以调用addFilter增加fc2 18 fc1.addFilter(fc2); 19 20 processor.setFilterChain(fc1); 21 22 String result = processor.process(); 23 System.out.println(result); 24 25 } 26 27 }
三、运行结果
时间: 2024-11-08 10:31:43