对请求的发送者和接收者进行解耦,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 "); } } }