Java-马士兵设计模式学习笔记-责任链模式-处理数据

一、目标

数据提交前做各种处理

 

二、代码

1.MsgProcessor.java

 1 public class MsgProcessor {

 2     

 3     private List<Filter> filters = new ArrayList<Filter>();

 4     private String msg;

 5     

 6     public String getMsg() {

 7         return msg;

 8     }

 9 

10     public void setMsg(String msg) {

11         this.msg = msg;

12     }

13 

14     public String process() {

15         

16         filters.add(new SensitiveFilter());

17         filters.add(new HTMLFilter());

18         

19         String r = msg;

20         for(Filter f : filters){

21             r = f.doFilter(r);

22         }

23         return r;

24     }

25 }

 

2.Filter.java

1 public interface Filter {

2     public String doFilter(String str);

3 }

 

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

public class SensitiveFilter implements Filter {



    @Override

    public String doFilter(String str) {

        return str.replace("敏感", "幸福");

    }



}

 

5.Test.java

public class Test {



    @org.junit.Test

    public void testFilter(){

        

        String msg = "<html>敏感字眼</html>"; 

        MsgProcessor processor = new MsgProcessor();

        processor.setMsg(msg);

        String result = processor.process();

        System.out.println(result);

        

    }



}

 

三、运行结果

你可能感兴趣的:(责任链模式)