一、目标

增加filterchain功能

二、代码

1.Filter.java

 public interface Filter {
public String doFilter(String str);
}

2.FilterChain.java

 import java.util.ArrayList;
import java.util.List; public class FilterChain implements Filter { private List<Filter> filters = new ArrayList<Filter>(); public String doFilter(String str) {
for(Filter f : filters){
str = f.doFilter(str);
}
return str;
} //把函数的返回值设为FilterChain,返回this,就能方便链式编写代码
public FilterChain addFilter(Filter filter) {
filters.add(filter);
return this;
} }

3.HTMLFilter.java

 public class HTMLFilter implements Filter {

     @Override
public String doFilter(String str) {
return str.replace('<', '[').replace(">", "]");
} }

4.SensitiveFilter.java

 public class SensitiveFilter implements Filter {

     @Override
public String doFilter(String str) {
return str.replace("敏感", "幸福");
} }

5.MsgProcessor.java

 public class MsgProcessor {

     //private List<Filter> filters = new ArrayList<Filter>();
FilterChain filterChain;
private String msg; public FilterChain getFilterChain() {
return filterChain;
} public void setFilterChain(FilterChain filterChain) {
this.filterChain = filterChain;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public String process() {
return filterChain.doFilter(msg);
}
}

6.Test.java

 public class Test {

     @org.junit.Test
public void testFilter(){ MsgProcessor processor = new MsgProcessor(); String msg = "<html>敏感字眼</html>";
processor.setMsg(msg); FilterChain fc1 = new FilterChain();
fc1.addFilter(new HTMLFilter()); FilterChain fc2 = new FilterChain();
fc2.addFilter(new SensitiveFilter()); //由于FilterChain实现了Filter接口,所以FilterChain同时也是Filter,所以可以调用addFilter增加fc2
fc1.addFilter(fc2); processor.setFilterChain(fc1); String result = processor.process();
System.out.println(result); } }

三、运行结果

Java-马士兵设计模式学习笔记-责任链模式-FilterChain功能-LMLPHP

04-30 07:23