Java中监听器的目的是什么? [英] What is the purpose of a listener in Java?

查看:458
本文介绍了Java中监听器的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找了这个,但找不到它究竟是什么的充分解释。我看到的是一个Java接口,它作为参数在另一个类中作为监听器传递。人们将各种监听器添加到列表中,并通过单个方法调用它们。

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 class as a "Listener". People added various listeners to a list and called them all through a single method.

我不知道为什么要使用它。有人可以解释吗?

I'm not sure why I would use it. Can someone care to explain?

这是我原来的帮助帖子,有人告诉我使用听众。

This is my original help post where someone told me to use listeners.

链接

推荐答案

在链接 KillMonsterEventListener

public interface KillMonsterEventListener {
    void onKillMonster ();
}

为您的API用户提供了一种告诉您这样的方式:

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()
}

我的代码片段(即 monsterCount - 和打印输出)都被执行了。关于它的好处是你的代码与我的代码完全分离:它不知道我在打印什么,我正在减少什么变量,等等。

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.

这篇关于Java中监听器的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆