1

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?

Community
  • 1
  • 1
Phuc
  • 623
  • 1
  • 7
  • 11

2 Answers2

3

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).

dsh
  • 12,037
  • 3
  • 33
  • 51
0

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
dsh
  • 12,037
  • 3
  • 33
  • 51
Sanj
  • 3,879
  • 2
  • 23
  • 26