我正在寻找一个 Java 模式, 用来进行嵌套式的无阻截方法呼叫。 在我的例子中, 某些客户代码需要不同步地援引一个服务来进行某种使用案例, 而该使用案例的每一个步骤本身都必须不同步地进行( 原因不属于本问题范围 ) 。 想象一下我现有的接口如下:
public interface Request {}
public interface Response {}
public interface Callback<R extends Response> {
void onSuccess(R response);
void onError(Exception e);
}
request
和 Response
界面有各种对称执行,即 requestA
+ ResponseA
(客户端提供), requestB
+ ResponseB
(服务内部使用),等等。
处理流程看起来是这样的:
"https://i.sstatic.net/egQJX.png" alt="序列图,显示嵌套回拨。"/ >
从收到每份答复到发出下一份请求之间,还需要进行一些额外的处理(例如,根据以前任何要求或答复中的数值)。
到目前为止,我尝试了两种方法 来在爪哇的编码:
- anonymous classes: gets ugly quickly because of the required nesting
- inner classes: neater than the above, but still hard for another developer to comprehend the flow of execution
是否有某种模式可以让该代码更容易读取? 例如,我能否将服务方法表达为一份由某个负责筑巢的框架类别按顺序执行的自足操作清单?