是否可以使用回调设置多个侦听器?
我试图理解回调是如何工作的,我试图找出它是我需要的。
我有一个接收/发送消息的UDP消息传递类。当我解析某些消息时,我想更新多个UI类。
目前我有这样的事情:
class CommInt {
private OnNotificationEvent notifListener;
public setNotificationListener(OnNotificationEvent notifListner) {
/* listener from one UI */
this.notifListener = notifListener;
}
private parseMsg(Message msg) {
if (msg.getType() == x) {
notifListener.updateUI();
}
}
}
我还需要更新另一个用户界面。另一个UI将使用相同的界面,但正文将是不同的。
如何调用从该接口实现的所有侦听器?
答案 0 :(得分:3)
您很可能需要创建一个侦听器列表,然后遍历每个调用updateUI()
的侦听器。当然,您还需要一个addListener()
方法,以便不会覆盖。
class CommInt {
private List <OnNotificationEvent> listeners= new ArrayList <OnNotificationEvent>();
public void addNotificationListener(OnNotificationEvent notifListner) {
listeners.add (notifListener);
}
private void parseMsg(Message msg) {
if (msg.getType() == x) {
for (notifListener : listeners){
notifListener.updateUI();
}
}
}
}
答案 1 :(得分:0)
使用您的代码:否,因为您使用单个变量进行录制。用可变长度的容器替换它,并且需要尽可能多的监听器:
class CommInt {
private ArrayList<NotificationListener> listeners =
new ArrayList<NotificationListener>();
public addNotificationListener(NotificationListener listener) {
listeners.add(listener);
}
private doSomething(Something input) {
if (input.hasProperty(x)) {
for (NotificationListener l: listeners) {
l.inputHasProperty(x);
}
}
}
}
还要注意不同的命名。 Java约定是按照它们的原样或事物来调用它们。如果您有一个监听器列表,请让它们实现NotificationListener接口并将它们存储起来。
此外,“set”现在是一个“add”(因为我们可以添加无限数量),并且回调是在我们执行的测试之后命名的,以确定是否需要回调。这样可以保持代码清洁,因为它会强制您的方法名称及其中的代码有意义。
“updateUI”基于“message is type ...”没有多大意义,而“msg.type = Message.CLEAR_DIALOGS”上的“l.clearDialogs()”会。