实现多个通用接口 [英] Implementing multiple generic interfaces
本文介绍了实现多个通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要处理两种不同类型的事件,但我遇到了以下问题:
接口EventListener不能多次使用不同的参数实现: EventListener< PriceUpdate>
和 EventListener< OrderEvent>
。
有没有一个优雅的解决方案呢?
public interface EventListener< E> {
public void handle(E event);
}
public interface PriceUpdateEventListener扩展EventListener< PriceUpdate> {
}
public interface OrderEventListener扩展EventListener< OrderEvent> {
}
public class CompositeListener实现OrderEventListener,PriceUpdateEventListener {
....
}
解决方案
现实中只有一个句柄(Object)方法。您实际上写的是相同的
public class CompositeListener implements EventListener {
public void handle(Object event){
if(事件instanceof PriceUpdate){
///
} else if(event instanceof OrderEvent){
///
}
}
}
如果没有这种检查逻辑,在任何情况下都无法有效地调用事件侦听器。 / p>
I need to handle events of two different types but I'm running into the following issue:
The interface EventListener cannot be implemented more than once with different arguments: EventListener<PriceUpdate>
and EventListener<OrderEvent>
.
Is there an elegant solution for this?
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 {
....
}
解决方案
There is only one handle(Object) method in reality. You are effectively write the same as
public class CompositeListener implements EventListener {
public void handle(Object event) {
if (event instanceof PriceUpdate) {
///
} else if (event instanceof OrderEvent) {
///
}
}
}
Without this checking logic, you can't effectively call your event listener in any case.
这篇关于实现多个通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文