gpt4 book ai didi

java - 在使用 Java 泛型方面需要一些帮助

转载 作者:搜寻专家 更新时间:2023-10-31 20:15:17 24 4
gpt4 key购买 nike

我正在尝试创建一个系统来响应我的应用程序中发生的事件,类似于观察者模式。在我的系统中,EventProducer s 触发事件和 EventConsumer s 响应这些事件,两者通过中央集线器连接:

目前,我将忽略 EventProducer并关注 EventHubEventConsumer :

interface EventConsumer<E extends Event> {
void respondToEvent(E event);
}

class EventHub {
private HashMap<Class</*event type*/>, HashSet<EventConsumer</*event type*/>>> subscriptions;
public <E extends Event> void fireEvent(E event) {
/* For every consumer in the set corresponding to the event type {
consumer.respondToEvent(event);
} */
}
public <E extends Event> void subscribeToEvent(EventConsumer<E> consumer) {
/* Insert consumer into the set corresponding to E */
}
}

问题出在HashMap的声明上: 我希望能够做类似的事情

HashMap<Class<E extends Event>, HashSet<EventConsumer<E>>>
// or
<E extends Event> HashMap<Class<E>, HashSet<EventConsumer<E>>>

所以 EventConsumer由相同类型参数化 Class是,但我能得到的最接近的是

HashMap<Class<? extends Event>, HashSet<EventConsumer<? extends Event>>>

但是这将允许像 HashSet<EventConsumer<MouseClickEvent>> 这样的事情被分配给 Class<KeyPressEvent> ,假设两者都是 KeyPressEventMouseClickEvent子类 Event .

第二个问题在 subscribeToEvent : 我需要能够将消费者存储在与其事件相对应的正确集合中,例如

subscriptions.get(E.class).put(consumer)

但我无法在运行时获取 E 类。

如何解决这些问题?我是不是用错了方法?

最佳答案

您可以做的是用它自己的参数化类包装 Map。将参数提供给类 - 您可以在 map 中使用它。类似的东西:

public class EventsMap<E extends Event> {
HashMap<Class<E>, HashSet<E>> map;
}

至于订阅 - 我将使用 ty1824 的答案..

关于java - 在使用 Java 泛型方面需要一些帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839468/

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