Implementation of several common interfaces

I need to handle events of two different types, but I have the following problem:

The EventListener interface 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 { .... } 
+4
source share
2 answers

In fact, there is only one handle (Object) method. You actually write the same thing as

 public class CompositeListener implements EventListener { public void handle(Object event) { if (event instanceof PriceUpdate) { /// } else if (event instanceof OrderEvent) { /// } } } 

Without this validation logic, you cannot effectively call an event listener anyway.

+6
source

I am trying to do the same in my project, and there seems to be no elegant way to do this. The problem is that all different versions of common interface methods have the same name and may have the same argument as for them. At least if you use subclasses, and since there is no guarantee that you will not do this, it will not compile. At least what I think is happening.

 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){ }} 

In this example, if something calls a ClassWithBoth method called method with an argument that is Fraction, it must select methods 2, both will work as Fraction as well as Number. Doing something like this is stupid, but there is no guarantee that people do not, and if they work, Java will not know what to do.

The β€œsolution” I came up with is to rename functions like this.

 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){ }} 

Unfortunately, this view eliminates the hole point at which there is a GenericInterface in the first place, since you cannot use it.

0
source

All Articles