Java中的嵌套回调

Java中的嵌套回调

本文介绍了Java中的嵌套回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找制造的非阻塞方法调用嵌套序列的Java模式。在我的情况下,一些客户端code需要异步调用服务来执行一些用例,并且本身必须异步执行该用例的每一步(此问题的范围之外的原因)。想象一下,我有现有的接口如下:

I'm looking for a Java pattern for making a nested sequence of non-blocking method calls. In my case, some client code needs to asynchronously invoke a service to perform some use case, and each step of that use case must itself be performed asynchronously (for reasons outside the scope of this question). Imagine I have existing interfaces as follows:

public interface Request {}

public interface Response {}

public interface Callback<R extends Response> {
    void onSuccess(R response);
    void onError(Exception e);
}

有在请求的各种配对实施响应接口,即 RequestA + ResponseA (由客户提供), RequestB + ResponseB (由服务内部使用)等。

There are various paired implementations of the Request and Response interfaces, namely RequestA + ResponseA (given by the client), RequestB + ResponseB (used internally by the service), etc.

的处理流程是这样的:

在收到每个响应和下一请求的发送之间,一些额外的处理需要发生(例如,基于任何的previous请求或响应的值)。

In between the receipt of each response and the sending of the next request, some additional processing needs to happen (e.g. based on values in any of the previous requests or responses).

到目前为止,我已经试过两种方法在Java编码是:

So far I've tried two approaches to coding this in Java:


  • 匿名类:很快得到难看,因为所需的嵌套

  • 内部类:整洁比以上,但仍难以另一家开发商对COM prehend执行流程

有一些模式,使这个code更具可读性?例如,可能我前preSS作为按顺序由一些框架类,它嵌套照顾执行自成体系的操作列表的服务方法?

Is there some pattern to make this code more readable? For example, could I express the service method as a list of self-contained operations that are executed in sequence by some framework class that takes care of the nesting?

推荐答案

实施以来(不仅界面)不得阻止,我喜欢你的列表的想法。

Since the implementation (not only the interface) must not block, I like your list idea.

设置操作(也许未来 S'),其设置应为pretty清晰可读的列表。然后在接收到的每个响应,下一个操作应被调用。

Set up a list of "operations" (perhaps Futures?), for which the setup should be pretty clear and readable. Then upon receiving each response, the next operation should be invoked.

随着一点点想象力,这听起来像是责任的链。下面是一些伪code为我想象什么:

With a little imagination, this sounds like the chain of responsibility. Here's some pseudocode for what I'm imagining:

public void setup() {
    this.operations.add(new Operation(new RequestA(), new CallbackA()));
    this.operations.add(new Operation(new RequestB(), new CallbackB()));
    this.operations.add(new Operation(new RequestC(), new CallbackC()));
    this.operations.add(new Operation(new RequestD(), new CallbackD()));
    startNextOperation();
}
private void startNextOperation() {
    if ( this.operations.isEmpty() ) { reportAllOperationsComplete(); }
    Operation op = this.operations.remove(0);
    op.request.go( op.callback );
}
private class CallbackA implements Callback<Boolean> {
    public void onSuccess(Boolean response) {
        // store response? etc?
        startNextOperation();
    }
}
...

这篇关于Java中的嵌套回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!