实现多个通用接口

5

我需要处理两种不同类型的事件,但是我遇到了以下问题:

接口EventListener不能使用不同的参数实现多次:EventListener<PriceUpdate>EventListener<OrderEvent>

是否有一个优雅的解决方案?

public interface EventListener <E> {
    public void handle(E event);
}
public interface PriceUpdateEventListener extends EventListener<PriceUpdate> {
}
public interface OrderEventListener extends EventListener<OrderEvent> {
}

public class CompositeListener implements OrderEventListener,PriceUpdateEventListener {
....
}

您可以通过提供通用方法addEventListener()在运行时使其更具动态性。但我认为您的解决方案已经很优雅了。 - d1e
你的解决方案看起来不错,但是让一个类处理这两个(相当)不相关的事件有意义吗? - assylias
3
如果一个解决方案甚至无法编译,那么它如何能够既完美又优雅呢? - Thilo
请检查此答案:https://dev59.com/lnM_5IYBdhLWcg3wn0rT - Amin Abbaspour
2个回答

6
实际上只有一个句柄(Object)方法。你实际上写的是相同的。
public class CompositeListener implements EventListener {
    public void handle(Object event) {
        if (event instanceof PriceUpdate) {
            ///
        } else if (event instanceof OrderEvent) {
            ///
        }
    }
}

如果没有这个检查逻辑,你就无法在任何情况下有效地调用事件监听器。


0

我正在尝试在我的项目中做同样的事情,但似乎没有任何优雅的方法来实现它。问题在于所有不同版本的通用接口方法都具有相同的名称,并且可以应用相同的参数。至少如果您正在使用子类,而且不能保证您不会使用子类,则它将无法编译。至少我认为是这样发生的。

class Fraction extends Number{
...
}
GenericInteface <T> {
void method(T a);
}

NumberInterface extends GenericInteface <Number>{
}
FractionInterface extends GenericInteface <Fraction>{
}
ClassWithBoth implements NumberInterface, FractionInterface{
void method(Number a){
}
void method(Fraction a){
}}

在这个例子中,如果有什么东西调用了ClassWithBoth的名为method的方法,并且参数是一个Fraction,它将有两种选择的方法,因为Fraction也是Number。像这样做很愚蠢,但不能保证人们不会这样做,如果他们这样做,Java将不知道该怎么办。
我想到的“解决方案”是重新命名函数,像这样。
class Fraction extends Number{
...
}
GenericInteface <T> {
void method(T a);
}
NumberInterface {
void numberMethod(Number a);
}
FractionInterface {
void fractionMethod(Fraction a);
}
ClassWithBoth implements NumberInterface, FractionInterface{
void numberMethod(Number a){
}
void fractionMethod(Fraction a){
}}

很遗憾,这有点否定了一开始使用通用接口的初衷,因为你无法真正使用它。

是的,这并不是真正的解决方案! - DD.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接