What is the purpose of a listener in Java?

In the code example that you linked the KillMonsterEventListener

public interface KillMonsterEventListener {
    void onKillMonster ();
}

provides a way for users of your API to tell you something like this:

Here is a piece of code. When a monster is killed, call it back. I will decide what to do.

This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            System.out.println("A good monster is a dead monster!");
        }
    }
);

Somewhere else I could add another listener:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            monsterCount--;
        }
    }
);

When your code goes through the list of listeners on killing a monster, i.e.

for (KillMonsterEventListener listener : listeners) {
    listener.onKillMonster()
}

both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.

Leave a Comment