The Chain Of Responsibility 1

                       

今天分享一下,设计模式中的责任链模式,其余的不过多叙述。


思路

在正式接触责任连之前,我们可以想象到的应该是一个链,链表?要处理一件事需要一个链似得?其实答案差不多就是这样。设计模式也都是从朴素的思维中经过一系列的总结得到的。下面来谈一谈责任链的进化之路。

来源

责任链也是从实际的开发中不断升华得到的一个“套路”,这也是称之为“模式”的原因了。比如说,我们现在要对用户上传的数据进行过滤。要实现这样的一个功能,我们首先想到的可能是下面这样的。

// 待处理的用户的输入数据        String message = "<script>while(1){alert('HaHa,敏感词,替换词')</script>";         String result = message.replaceAll("<","[");         result = result.replaceAll(">","]");        System.out.println("未被处理的数据为:" + message);        System.out.println("经过处理的数据为:" + result);
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

很简单了吧,但是想一想,这样真的够了吗?

 

其实String类的设计就是一个链的模式,这点我们可以从replaceAll方法中看出一点端倪。

加大点难度

现在假如说添加了一个更加高级点的功能,那就是实现对HTML的代码的转义,敏感词的过滤,替换词的替换等等。那么如果我们还这样写的话,这个方法体就会变的很大,而且不容易进行维护。而根据面向对象的思维,我们不难想到抽象出一个接口,要想实现哪种功能,就直接让其实现这个接口完成相应的业务逻辑就好了嘛。

下面我们就来看看这种实现。
首先是接口:Filter.java

package ResponsibilityChain;public interface Filter {    public String doFilte(String message);}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

HTMLFilter.java

package ResponsibilityChain;/** * HTML filter utility. *  * 但是也添加了一些修改内容 * * @author Craig R. McClanahan * @author Tim Tye */public final class HTMLFilter implements Filter{    /**     * Filter the specified message string for characters that are sensitive in     * HTML. This avoids potential attacks caused by including JavaScript codes     * in the request URL that is often reported in error messages.     *     * @param message     *            The message string to be filtered     */    public String doFilte(String message) {        if (message == null)            return (null);        char content[] = new char[message.length()];        message.getChars(0, message.length(), content, 0);        StringBuilder result = new StringBuilder(content.length + 50);        for (int i = 0; i < content.length; i++) {            switch (content[i]) {            case '<':                result.append("&lt;");                break;            case '>':                result.append("&gt;");                break;            case '&':                result.append("&amp;");                break;            case '"':                result.append("&quot;");                break;            default:                result.append(content[i]);            }        }        return (result.toString());    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

SesitiveFilter.java

package ResponsibilityChain;public final class SesitiveFilter implements Filter {    @Override    public String doFilte(String message) {        // 正常来说应该是个词库的,对词库中的数据进行匹配,这样比较合理一些,此处为了掩饰核心思想,就简化了这个操作        String str = message.replaceAll("敏感词", "不敏感了");        return str;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

ReplacableFilter.java

package ResponsibilityChain;public class ReplacableFilter implements Filter {    @Override    public String doFilte(String message) {        // 正常来说应该是个词库的,对词库中的数据进行匹配,这样比较合理一些,此处为了掩饰核心思想,就简化了这个操作        String str = message.replaceAll("替换词", "已被替换");        return str;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

然后是一个业务逻辑的管家了,它负责接收要进行过滤的数据,并且返回处理过的数据,MyProcessor.java

package ResponsibilityChain;public class MyProcessor {    private String msg;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public String process() {        // 调用相关的过滤器进行词汇的过滤        HTMLFilter htmlFilter = new HTMLFilter();        String result = htmlFilter.doFilte(msg);        // 调用敏感词过滤器        SesitiveFilter sesitiveFilter = new SesitiveFilter();        result = sesitiveFilter.doFilte(result);        ReplacableFilter replacableFilter = new ReplacableFilter();        result = replacableFilter.doFilte(result);        return result;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

最后来个测试吧。Main.java

package ResponsibilityChain;public class Main {    public static void main(String[] args) {        // 待处理的用户的输入数据        String message = "<script>while(1){alert('HaHa,敏感词,替换词')</script>";         MyProcessor myProcessor = new MyProcessor();         myProcessor.setMsg(message);         String result = myProcessor.process();        System.out.println("未被处理的数据为:" + message);        System.out.println("经过处理的数据为:" + result);    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
 

小总结
   这样就可以实现我们需要的功能了,我们可以在MyProcessor类中添加我们的过滤器,完成所有我们需要的功能。但是看一下,

public String process() {        // 调用相关的过滤器进行词汇的过滤        HTMLFilter htmlFilter = new HTMLFilter();        String result = htmlFilter.doFilte(msg);        // 调用敏感词过滤器        SesitiveFilter sesitiveFilter = new SesitiveFilter();        result = sesitiveFilter.doFilte(result);        ReplacableFilter replacableFilter = new ReplacableFilter();        result = replacableFilter.doFilte(result);        return result;    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这段代码,总是感觉有点冗余,给人的感觉就是有点笨重了。下面我们就来解决一下这个问题。

责任链前身

为了解决上面的代码过于冗余,下面引入了责任链的前身,那就是使用一个数组保存我们所有的Filter的实现类,用于管理我们的过滤任务。我们只需要在MyProcessor类中进行修改即可。
如下,MyProcessor2.java

package ResponsibilityChain;public class MyProcessor2 {    Filter[] filters = { new HTMLFilter(), new SesitiveFilter(), new ReplacableFilter() };    private String msg;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public String process() {        String result = msg;        for (Filter f : filters) {            result = f.doFilte(result);        }        return result;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

测试一下:

package ResponsibilityChain;public class Main2 {    public static void main(String[] args) {        // 待处理的用户的输入数据        String message = "<script>while(1){alert('HaHa,敏感词,替换词')</script>";        MyProcessor2 myProcessor2 = new MyProcessor2();        myProcessor2.setMsg(message);        String result = myProcessor2.process();        System.out.println("未被处理的数据为:" + message);        System.out.println("经过处理的数据为:" + result);    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
 

小总结:这里我们明显的可以看到使用了数组来进行管理的好处了吧,我们只需要在添加新的过滤器实现类的时候在这个数组里面就可以了。
  这样看着,有点意思了吧。

责任链出山

看完了上面的代码,想必对这个业务逻辑很熟悉了吧。但是这还不是我们的责任链模式,没有体现出“链”的特点,而且假如说我们有两个这样的数组,要合作的完成过滤任务,而且是在一个完成一半的时候插入另一个数组的任务,这样的话,就比较的棘手了吧。所以下面要交给责任链来进行管理了。
FilterChain.java

package ResponsibilityChain;import java.util.ArrayList;import java.util.List;public class FilterChain implements Filter{    private List<Filter> filters = new ArrayList<Filter>();    /**     * return itself for better usage the Chain     *      * @param f     * @return     */    public FilterChain addFilter(Filter f) {        filters.add(f);        return this;    }    public void remove(Filter f) {        filters.remove(f);    }    /**     * For the chain , it's also a chain for filter     *      * @param message     *            message need to be filtered     * @return     */    public String doFilte(String message) {        String result = message;        for (Filter f : filters) {            result = f.doFilte(result);        }        return result;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

这样一来,MyProcessor也要进行修改,如MyProcessor3.java

package ResponsibilityChain;public class MyProcessor3 {    private FilterChain filterChain;    public FilterChain getFilterChain() {        return filterChain;    }    public void setFilterChain(FilterChain filterChain) {        this.filterChain = filterChain;    }    private String msg;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    // 此处为核心and关键    public String process() {        String result = msg;        result = filterChain.doFilte(result);        return result;    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

再来测试一把,Main3.java

package ResponsibilityChain;public class Main3 {    public static void main(String[] args) {        // 待处理的用户的输入数据        String message = "<script>while(1){alert('HaHa,敏感词,替换词')</script>";        MyProcessor3 myProcessor3 = new MyProcessor3();        myProcessor3.setMsg(message);        FilterChain filterChain = new FilterChain();        // filterChain.addFilter(new HTMLFilter());        // filterChain.addFilter(new SesitiveFilter());        // filterChain.addFilter(new ReplacableFilter());        myProcessor3.setFilterChain(filterChain);        // 作为一个链的方式进行添加过滤器,这就是链式编程的好处        filterChain.addFilter(new HTMLFilter()).addFilter(new SesitiveFilter()).addFilter(new ReplacableFilter());        String result = filterChain.doFilte(message);           System.out.println("未被处理的数据为:" + message);        System.out.println("经过处理的数据为:" + result);    }}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

这里就需要好好的来个总结了,经典的思想总是让人感叹啊。
不知道你有没有注意到在FilterChain.java中

public FilterChain addFilter(Filter f) {        filters.add(f);        return this;    }
  
  
  • 1
  • 2
  • 3
  • 4

这个方法就可以完成“链”的效果。返回自身,这样就可以不断的调用同样的方法,链式的完成任务。
还有FilterChain也有一个doFilte的方法,也就是说我们将完成过滤的功能从MyProcessor.java类中迁移到了FilterChain类中了。

而且实现了Filter接口的FilterChain也就可以完成添加更加自由的过滤规则了。

 

这就是面向对象的核心,一个对象能完成什么功能完全取决于其自身的属性。

这样我们在MyProcessor3.java中只需要调用责任链的这个过滤功能就可以了。

总结

本文从一个现实中的问题出发,从简单的朴素的思想,一步步的经过面向对象的强化以及经典的责任链思想的牵引。完成了一个简单的责任链模式的小例子。

如果细心的品味一下,肯定会有不少感触的吧。责任链模式在实际的开发过程中也是很常见的,比如说Struts2的拦截器栈等等。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值