Classes that are source of events for listeners of different interfaces

0

Talking about personalized events by the user. In the case that a class is a source of events for listeners that implement different interfaces, I create a list of listeners and in the event distribution loop I discriminate to the interface that I want to send the event to (through instanceof), or on the contrary I think several lists, one for each type of listener? Thanks

    
asked by José Espejo Roig 12.02.2018 в 09:12
source

1 answer

0

Suppose a class% co_of% whose objects can throw two types of events: MiClase and Evento1 .

Suppose also that we have an interface Evento2 and another interface Evento1Listener , that have defined the methods Evento2Listener and cuandoEvento1 , respectively.

Now imagine that I have two instances cuandoEvento2 , and one instance of a class that meets both interfaces, but I want you to listen to the events MiClase of one of the instances of Evento1 and events eventto2 of the other instance:

class MiListener implements Evento1Listener, Evento2Listener { 

    void cuandoEvento1(Evento1 e) {
        ...
    }
    void cuandoEvento2(Evento2 e) {
        ...
    }

}


MiClase obj1= new MiClase();
MiClase obj2= new MiClase();
MiListener l= new MiListener();

obj1.addEvento1Listener(l);
obj2.addEvento2Listener(l);

As you can see, looking at what interface implements does not help at all, you should save the listeners in different queues (l could be in both). It is common for a class to implement more than one interface: when designing a UI with Swing, the container usually listens to the events of the contained elements in order to be able to act on others.

    
answered by 12.02.2018 в 10:04