What is the purpose of a listener in Java?

后端 未结 7 465
再見小時候
再見小時候 2020-12-04 20:23

I looked for this online, but couldn\'t find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another cla

相关标签:
7条回答
  • 2020-12-04 21:12

    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.

    0 讨论(0)
提交回复
热议问题