29 Sep 2014

Java设计模式:责任链模式

注:本文为译文,原文出处java-design-patterns-in-stories

责任链模式的主要思想是构建一个处理单元的链条, 如果满足某一阀值则每一个单元都将处理此请求. 由于创建了一个链, 如果一个单元满足阀值, 那么它的下一个单元就将被尝试, 以此类推. 每个请求都将沿着链被处理.

责任链模式类图

chain-of-responsibility-pattern-class-diagram

责任链模式Java代码

package designpatterns.cor;

abstract class Chain {
    public static int One = 1;
    public static int Two = 2;
    public static int Three = 3;
    protected int Threshold;

    protected Chain next;

    public void setNext(Chain chain) {
        next = chain;
    }

    public void message(String msg, int priority) {
        //if the priority is less than Threshold it is handled
      if (priority <= Threshold) {
            writeMessage(msg);
        }

        if (next != null) {
            next.message(msg, priority);
        }
    }

    abstract protected void writeMessage(String msg);
}

class A extends Chain {
    public A(int threshold) {
        this.Threshold = threshold;
    }

    protected void writeMessage(String msg) {
        System.out.println("A: " + msg);
    }
}


class B extends Chain {
    public B(int threshold) {
        this.Threshold = threshold;
    }

    protected void writeMessage(String msg) {
        System.out.println("B: " + msg);
    }
}

class C extends Chain {
    public C(int threshold) {
        this.Threshold = threshold;
    }

    protected void writeMessage(String msg) {
        System.out.println("C: " + msg);
    }
}


public class ChainOfResponsibilityExample {

    private static Chain createChain() {
        // Build the chain of responsibility

      Chain chain1 = new A(Chain.Three);

      Chain chain2 = new B(Chain.Two);
      chain1.setNext(chain2);

        Chain chain3 = new C(Chain.One);
        chain2.setNext(chain3);

        return chain1;
    }

    public static void main(String[] args) {

      Chain chain = createChain();

        chain.message("level 3", Chain.Three);

        chain.message("level 2", Chain.Two);

        chain.message("level 1", Chain.One);
    }

}

这个例子中, level 1遍历了责任链中的所有单元.

A: level 3
A: level 2
B: level 2
A: level 1
B: level 1
C: level 1

译者补充

JDK中的责任链模式

JDK在异常捕获机制中使用了责任链模式, 当方法出现异常时, 首先会被当前方法的catch代码块, 如果当前方法不能处理这个异常, 那么可以继续抛出异常, 异常就会被调用当前方法的方法中的catch块捕获, 以此类推.
同样, 大家熟知的Servlet中的Filter也基于责任链模式, 创建自定义的过滤器需要实现Filter接口的doFilter(ServletRequest request, ServletResponse response, FilterChain chain)方法, 在方法实现中可以自由控制是否继续下一个过滤器的处理, 可以通过调用chain.doFilter(request, response);把请求与响应发送给下一个过滤器, 从而达到对责任链的遍历.


Tags:
0 comments