2012-07-02 60 views
4

我需要處理兩種不同類型的事件,但我遇到了以下問題:實現多個通用接口

接口的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 { 
.... 
} 
+0

通過提供泛型方法addEventListener(),可以使其在運行時更具動態性。但我認爲你的解決方案已經很優雅了。 – JMelnik

+0

你的解決方案看起來很好,但是有一個類處理那些2(相當)不相關的事件是否有意義? – assylias

+3

@JMelnki,assylias:如果解決方案甚至沒有編譯,該如何解決問題? – Thilo

回答

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與這是一個分數參數方法命名的方法,它有方法2選擇從,雙方將努力爲分數也是一個號碼。做這樣的事情是愚蠢的,但沒有保證人們不會這樣做,並且如果他們這樣做,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){ 
}} 

不幸的是,有點消除了首先有GenericInterface的漏洞,因爲你不能真正使用它。

+0

是的......這不是一個真正的解決方案! –