Java 中侦听器的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31625962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the purpose of a listener in Java?
提问by Jacob Macallan
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.
我在网上找了这个,但找不到它到底做了什么的充分解释。我看到的是一个 Java 接口,它作为参数在另一个类中作为“侦听器”传递。人们将各种侦听器添加到列表中,并通过单一方法调用它们。
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.
这是我最初的帮助帖子,有人告诉我使用监听器。
采纳答案by dasblinkenlight
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, 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.
我的代码片段(即monsterCount--
和打印输出)都被执行。它的好处是你的代码与我的完全分离:它不知道我在打印什么,我在减少什么变量,等等。
回答by Christopher Oezbek
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.
使用侦听器让其他代码通知您“条件”/“事件”。例如,如果鼠标已被移动/点击/拖动,则可以调用“鼠标侦听器”。这取决于您的应用程序为什么提供侦听器。
回答by Sachin Tanna
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. It calls actionPerformed() method when an event occurs. You can refer http://java.about.com/od/a/g/Actionlistener.htmfor more info.
当事件发生时,监听器会做一些工作。它们被称为“事件监听器”。单击、悬停等事件。例如,我们有 Java 中的 ActionListener 接口。它在事件发生时调用 actionPerformed() 方法。您可以参考http://java.about.com/od/a/g/Actionlistener.htm了解更多信息。
回答by jakubbialkowski
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.
侦听器用于通知状态更改。在大多数情况下,您可以将 Listeners 视为 Observers,因此每次发生有趣的事情时,都会调用您的 Listeners。
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
回答by Hoopje
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. Each GUI widget is implemented by a class. When you want to handle e.g. mouse clicks from the user, you add a listener (also called event handler) to GUI widget. 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. (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 编程中经常使用。每个 GUI 小部件都由一个类实现。当您想要处理例如来自用户的鼠标点击时,您可以向 GUI 小部件添加一个侦听器(也称为事件处理程序)。当用户单击小部件时,小部件将事件发送到注册的侦听器,以便应用程序可以响应鼠标单击。这将框架(GUI 小部件类)和应用程序代码分开。(在某些 GUI 框架中,例如 Swing,您可以向一个对象添加任意数量的侦听器;在其他框架中,您只能指定一个。)
Also in other areas event-driven programming is useful. You might want to observe an object (see Observer pattern). 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.
在其他领域,事件驱动编程也很有用。您可能想要观察一个对象(请参阅观察者模式)。例如,支持此功能的集合可能会在其内容更改时发送事件。如果发生这种情况,您需要执行一些处理,您可以将自己添加为此类的侦听器。另一种方法是在每次向集合中添加项目时调用后处理,但这很容易出错。
回答by MartinCz
Listeneris a common form of implementing the observerdesign patterin Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.
侦听器是在 Java中实现观察者设计模式的一种常见形式。这种技术也称为回调,这是一个来自过程语言世界的术语。
Observersregister themselves by the observable, which in turn calls back the observerswhenever some event occurs or when they should be notified about something.
观察者通过observable注册自己,当发生某些事件或应该通知观察者某事时,观察者反过来会回调观察者。
Many framework libraries play the role of the observable, e.g.:
许多框架库扮演可观察者的角色,例如:
- You register yourself (i.e., 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!
回答by Sunil Garg
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