简体   繁体   English

Java中的侦听器的目的是什么?

[英]What is the purpose of a listener in 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". 我看到的是一个Java接口,它作为参数在另一个类中作为“侦听器”传递。 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. 这是我的原始帮助帖子,有人告诉我使用侦听器。

Link 链接

In the code example that you linked the KillMonsterEventListener 在您链接KillMonsterEventListener的代码示例中

public interface KillMonsterEventListener {
    void onKillMonster ();
}

provides a way for users of your API to tell you something like this: 为您的API用户提供了一种方法,可以告诉您以下信息:

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, ie 当您的代码遍历有关杀死怪物的侦听器列表时,即

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

both my code snippets (ie the monsterCount-- and the printout) get executed. 我的所有代码片段(即monsterCount--和打印输出)都被执行了。 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. 这样做的好处是您的代码与我的代码完全脱钩:它不知道我在打印什么,我在递减的变量等等。

Listener is a common form of implementing the observer design patter in Java. 侦听器是在Java中实现观察器 设计模式的一种常见形式。 This technique is also referred to as the callback , which is a term coming from the world of procedural languages. 此技术也称为回调 ,这是一个来自过程语言世界的术语。

Observers register themselves by the observable , which in turn calls back the observers whenever some event occurs or when they should be notified about something. 观察者通过observable进行注册,后者在发生某些事件或应通知他们某些事件时反过来回调观察者

Many framework libraries play the role of the observable, eg: 许多框架库都扮演着可观察的角色,例如:

  • You register yourself (ie, your implementation of the listener interface) as a listener of incoming messages in a messaging middleware. 您可以将自己(即,侦听器接口的实现)注册为消息传递中间件中传入消息的侦听器。
  • You register yourself as a listener of some changes made by the user in the operating system. 您将自己注册为用户在操作系统中所做的某些更改的侦听器。
  • You register yourself as a listener of GUI events, such as a button was click on. 您将自己注册为GUI事件的侦听器,例如单击了一个按钮。

Example in Java code: Java代码示例:

Part 1 - The observable entity 第1部分-可观察的实体

import java.util.LinkedList;
import java.util.List;

public class Observable {
    private List<Observer> observers;

    public Observable() {
        observers = new LinkedList<>();
    }

    public void addObsever(Observer observer) {
        observers.add(observer);
    }

    private  void notifyObservers(String whatHappened) {
        for (Observer observer : observers) {
            observer.onSomethingHappened(whatHappened);
        }
    }

    public void doSomeStuff() {
        // ...
        // Do some business logic here.
        // ...

        // Now we want to notify all the listeners about something.
        notifyObservers("We found it!");

        // ...
        // Do some business logic here
        // ...
    }
}

Part 2 - The observer/listener interface 第2部分-观察者/侦听器界面

public interface Observer {
    void onSomethingHappened(String whatHappened);
}

Part 3 - Basic implementation of the observer/listener interface 第3部分-观察者/侦听器界面的基本实现

public class MyObserver implements Observer {
    @Override
    public void onSomethingHappened(String whatHappened) {
        System.out.println(whatHappened);
    }
}

Part 4 - Putting it all together 第4部分-全部组合

public class Main {
    public static void main(String[] args) {

        // Create the observable.
        Observable myObservable = new Observable();

        // Create the observers (aka listeners).
        Observer myObserverA = new MyObserver();
        Observer myObserverB = new MyObserver();

        // Register the observers (aka listeners).
        myObservable.addObsever(myObserverA);
        myObservable.addObsever(myObserverB);

        myObservable.doSomeStuff();

    }
} 

And the result on standard output will be: 标准输出的结果将是:

We found it!
We found it!

This is part of a programming paradigm called event-driven programming . 这是称为事件驱动编程的编程范例的一部分。 Objects send messages to other objects on certain occasions, for example when they change. 对象在某些情况下(例如当它们更改时)将消息发送到其他对象。 This is used often in GUI programming. 这在GUI编程中经常使用。 Each GUI widget is implemented by a class. 每个GUI小部件都由一个类实现。 When you want to handle eg mouse clicks from the user, you add a listener (also called event handler) to GUI widget. 当您要处理例如用户的鼠标单击时,可以将侦听器(也称为事件处理程序)添加到GUI小部件。 When the user clicks on the widget, the widget sends the event to the registered listener(s) so that the application can respond to the mouse click. 当用户单击窗口小部件时,窗口小部件会将事件发送到已注册的侦听器,以便应用程序可以响应鼠标单击。 This seperates the framework (the GUI widget class) and the application code. 这将框架(GUI小部件类)和应用程序代码分开。 (In some GUI frameworks, such as Swing, you can add an arbitrary number of listeners to an object; in others, you can specify only one.) (在某些GUI框架(例如Swing)中,可以向对象添加任意数量的侦听器;在其他框架中,只能指定一个侦听器。)

Also in other areas event-driven programming is useful. 在其他领域,事件驱动的编程也很有用。 You might want to observe an object (see Observer pattern ). 您可能想要观察一个对象(请参阅Observer模式 )。 For example, a collection which supports this, might send an event if its contents change. 例如,一个支持此功能的集合可能会在其内容更改时发送一个事件。 If you need to perform some processing if this occurs, you can add yourself as a listener to this class. 如果发生这种情况需要执行某些处理,则可以将自己添加为此类的侦听器。 The alternative would be to call the post-processing every time you add an item to the collection, but this error-prone. 替代方法是每次将一个项目添加到集合时都调用后处理,但这很容易出错。

Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener. Servlet Listener用于侦听Web容器中的事件,例如,当您创建会话或在会话中放置属性,或者在另一个容器中钝化并激活时,要订阅这些事件,可以在web.xml中配置侦听器,例如HttpSessionListener。

Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc. 侦听器会触发一个实际的物理请求,该请求可以附加到应用服务器中的事件。使用侦听器,您可以跟踪应用程序级别,会话级别,生命周期更改,属性更改等。

You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur. 您可以通过定义侦听器对象来监视和响应Servlet生命周期中的事件,这些侦听器对象在发生生命周期事件时将调用其方法。

Here is the blog post for Servlet Listener http://array151.blogspot.in/2016/12/servlet-listener.html 这是Servlet侦听器的博客文章http://array151.blogspot.in/2016/12/servlet-listener.html

Use a listener to let other code inform you of "conditions"/"events". 使用侦听器,让其他代码将“条件” /“事件”通知您。 For instance a "mouse listener" could be called if the mouse would have been moved/clicked/dragged. 例如,如果鼠标将被移动/单击/拖曳,则可以调用“鼠标侦听器”。 It depends on your application why it provides for listeners. 这取决于您的应用程序为何提供侦听器。

Listeners do some work when an event occurs. 事件发生时,侦听器会做一些工作。 They are called as "Event Listeners". 它们被称为“事件监听器”。 Events like click, hover etc.. For Example, we have ActionListener interface in Java. 诸如单击,悬停等事件。例如,我们在Java中具有ActionListener接口。 It calls actionPerformed() method when an event occurs. 事件发生时,它将调用actionPerformed()方法。 You can refer http://java.about.com/od/a/g/Actionlistener.htm for more info. 您可以参考http://java.about.com/od/a/g/Actionlistener.htm了解更多信息。

Listeners are used for notify about state changes. 侦听器用于通知状态更改。 You can think about Listeners in most of time as Observers, so every time something interesting happen your listener will be called. 您通常可以将侦听器视为观察者,因此每次发生有趣的事情时,都会调用您的侦听器。

You can read more about patterns in Java on following websites: 您可以在以下网站上阅读有关Java模式的更多信息:

http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial

http://www.developer.com/java/implementing-behavioral-patterns-in-java.html http://www.developer.com/java/implementing-behavioral-patterns-in-java.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM