static interface Response { void process(); } static abstract class CallServiceHandler { CallServiceHandler nextHandle; abstract CallServiceHandler process(); protected final void callBackFn(Response responase ) { responase.process(); } protected final CallServiceHandler execute() { process(); if(nextHandle != null ){ nextHandle.process(); } return this; } protected final CallServiceHandler setNextHandle(CallServiceHandler nextHandle) { this.nextHandle = nextHandle; return this; } } static class RequestDnHandler extends CallServiceHandler { @Override CallServiceHandler process() { System.out.println("fetch data by url ...."); return this; } } static class ProcessDnHandler extends CallServiceHandler { @Override CallServiceHandler process() { System.out.println("json to map ..."); return this; } }
public static void main(String[] args) { CallServiceHandler requesthandler = new RequestDnHandler(); CallServiceHandler processHandler = new ProcessDnHandler(); requesthandler.setNextHandle(processHandler).execute().callBackFn(new Response() { public void process() { System.out.println("callback response.."); } }); }
以上是职责链模式模拟的一个客户端请求服务器数据的处理过程,首先通过URL请求后台service,之后对后台service处理的结果进行处理,最后设置callback完成页面渲染。
也可以给予对象的依赖设置 关系,设置数据流程处理关系。