设计模式之责任链模式

责任链模式的核心思想是让请求对象(Request)沿着链(chain)按照一定顺序(ordered)依次传递下去,链上的每个处理器(Filter)都有机会去处理请求(request)。 客户端只需把请求传递给链(chain)上的第一个处理器(filter)即可,至于被谁处理,客户端不care。

/**
 * Test.java
 *
 * @author zhanghui
 *
 */
public class Test {

    public static void main(String[] args) {
        FilterManager.service(new Request(), new Response());
    }

}

class Request {
}
class Response {
}
class FilterManager {
    
    private static Filter firstFilter = null;
    
    static {
        // 可以把所有的filter放到配置文件中,然后这里从配置文件中初始化所有filter
        Filter f1 = new MyFilter1();
        Filter f2 = new MyFilter2();
        Filter f3 = new MyFilter3();
        f1.setNextFilter(f2);
        f2.setNextFilter(f3);
        f3.setNextFilter(new NullFilter());
        
        firstFilter = f1;
    }
    
    public static void service(Request req, Response resp) {
        if (firstFilter != null) {
            firstFilter.process(req, resp);
        }
    }
}
interface Filter {
    void setNextFilter(Filter filter);
    void process(Request req, Response resp);
}

abstract class AbstractFilter implements Filter {
    protected Filter next;
    
    public void setNextFilter(Filter next) {
        this.next = next;
    }
}
class MyFilter1 extends AbstractFilter {
    public void process(Request req, Response resp) {
        System.out.println("before MyFilter1...");
        next.process(req, resp);
        System.out.println("after MyFilter1...");
    }
}
class MyFilter2 extends AbstractFilter {
    public void process(Request req, Response resp) {
        System.out.println("before MyFilter2...");
        next.process(req, resp);
        System.out.println("after MyFilter2...");
    }
}
class MyFilter3 extends AbstractFilter {
    public void process(Request req, Response resp) {
        System.out.println("before MyFilter3...");
        next.process(req, resp);
        System.out.println("after MyFilter3...");
    }
}
class NullFilter extends AbstractFilter {
    public void process(Request req, Response resp) {
        // do nothing
    }
}


 

运行结果:

before MyFilter1...
before MyFilter2...
before MyFilter3...
after MyFilter3...
after MyFilter2...
after MyFilter1...

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