Reputation: 743
The answer here shows the way to create a custom event in java. I understood the answer, but I am wondering why he is using HelloListener
interface? I don't think it is needed.
My code:
import java.util.ArrayList;
import java.util.List;
class Initiater {
private List<Responder> listeners = new ArrayList<Responder>();
public void addListener(Responder toAdd) {
listeners.add(toAdd);
}
public void sayHello() {
System.out.println("Hello!!");
for (Responder hl : listeners)
hl.someoneSaidHello();
}
}
class Responder {
public void someoneSaidHello() {
System.out.println("Hello there...");
}
}
public class Test {
public static void main(String[] args) {
Initiater initiater = new Initiater();
Responder responder = new Responder();
initiater.addListener(responder);
initiater.sayHello();
}
}
I think the code I wrote does the same thing. Can I do it like that?
Upvotes: 1
Views: 78
Reputation: 4029
Interface will enable you to have multiple flavors of Listeners.
interface HelloListener {
void someoneSaidHello();
}
class Responder implements HelloListener {
@Override
public void someoneSaidHello() {
System.out.println("Hello there...");
}
}
class AnotherResponder implements HelloListener {
@Override
public void someoneSaidHello() {
System.out.println("Hello from Responder 2");
}
}
initiater.add(new Responder());
initiater.add(new AnotherResponder());
Calling
initiater.sayHello();
will now output
Hello there...
Hello from Responder 2
Upvotes: 0
Reputation: 12213
You can do that, but it is not good design. The reason for using interfaces is to decouple the behavior. There is no need to use listeners if you have only one implementation and that implementation is referenced directly from the "initiator". The purpose of the listener is to decouple it: the "initiator" knows nothing of what a listener might do or what the listener might be (ie its class). Since Java is statically typed, an interface must be defined. Then the implementation of the listener can be separate. It could even be in a separate project and compiled separately (eg when creating a library).
Upvotes: 3