职责链模式

对请求的发送者和接收者进行解耦,Servlet 的 Filter就是采用职责链设计模式

public class Chain {

    List<ChainHandler> handlers = null;
    
    private int index = 0;
    
    public Chain(List<ChainHandler> handlers) {
        this.handlers = handlers;
    }

    public void process() {
        if(index >= handlers.size())
            return;
        handlers.get(index++).execute(this);
    }

}

 

public abstract class ChainHandler {

    public void execute(Chain chain) {
        process();
        chain.process();
    }
    
    protected abstract  void process();
    
    
}

 

public class ChainTest {
    public static void main(String[] args) {

        List<ChainHandler> handlers = Arrays.asList(
                   new ChainHandlerA(),
                   new ChainHandlerB(),
                   new ChainHandlerC()
                );
        
        Chain chain = new Chain(handlers);
        chain.process();
    }
    
    static class ChainHandlerA extends ChainHandler{
        @Override
        protected void process() {
            System.out.println("handle by ChainHandlerA ");
        }
    }
    
    static class ChainHandlerB extends ChainHandler{
        @Override
        protected void process() {
            System.out.println("handle by ChainHandlerB ");
        }
    }
    
    static class ChainHandlerC extends ChainHandler{
        @Override
        protected void process() {
            System.out.println("handle by ChainHandlerC ");
        }
    }
}

 

posted @ 2019-06-22 10:59  踏月而来  阅读(130)  评论(0编辑  收藏  举报