gpt4 book ai didi

java - Java 是否有与 boost 或 Qt 信号等效的信号?

转载 作者:行者123 更新时间:2023-12-01 10:37:12 26 4
gpt4 key购买 nike

标题中提到的功能有一个简单的目的:允许用户将一些事件监听器绑定(bind)到一个对象,该对象将在事件发生时调度所有事件监听器。

这个简单的概念当然可以这样实现:

public class EventEmitter extends ArrayList<Runnable>;

但我更喜欢一个更智能的发射器 - 理想情况下允许将参数传递给回调。 Runnable 当然没有任何参数。 Lambda 表达式的另一端确实有参数。

智能发射器允许您定义特定的回调参数:

EventEmitter<String, Boolean> emitter = new EventEmitter();

我的问题是这个东西是java库的一部分还是我必须自己实现它。在谷歌上,我只找到了一些java.awt.AWTEvent,但这不是事件调度程序。

我喜欢的伪代码:

// Requires lambdas with (File, int) signature
public final EventEmitter<File, int> downloadCompleteEvent;

新事件添加为:

downloaderClass.downloadCompleteEvent
.addListener(
(File file, int downloadTime)->System.out.println("Downloaded "+file.getAbsolutePath()+" in "+downloadTime+" seconds.")
);

并将事件分派(dispatch)为:

this.downloadCompleteEvent.dispatch(downloadedFile, elapsedTime);

最佳答案

在纯Java中,您可以使用CompletableFuture来表示当前正在执行的状态或工作。在未来,您可以添加一个或多个监听器,这些监听器将通过结果进行调用。

举例:

public CompletableFuture<DownloadResult> download() {
// computing a result async
CompletableFuture<DownloadResult> future = CompletableFuture.supplyAsync(/* your process*/);
return future;
}

future.thenAccept( (DownloadResult) r -> { ... } );
// will be called when process is done

另外,您可以通过EventBus进入Guava库感兴趣:https://github.com/google/guava/wiki/EventBusExplained

或者通过 RXJava 库:https://github.com/ReactiveX/RxJava/wiki/How-To-Use-RxJava

关于java - Java 是否有与 boost 或 Qt 信号等效的信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34604325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com