2013-02-23 88 views
3

是否可以使用回调设置多个侦听器?是否可以对多个侦听器进行回调?

我想了解回调是如何工作的,而且我试图弄清楚这就是我所需要的。

我有一个接收/发送消息的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为好。其他用户界面将使用相同的界面,但主体会有所不同。

如何调用从该接口实现的所有监听器?

回答

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

    } 

} 
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”(因为我们可以添加它们的数目无限),并且回调以我们执行的测试命名,以确定回调是否有必要。这会使代码保持清洁,因为它会强制您的方法名称和其中的代码有意义。

基于“message is type ...”的“updateUI”没有多大意义,而“msg.type = Message.CLEAR_DIALOGS”上的“l.clearDialogs()”会。

+0

谢谢。我写的代码只是一个例子,并不符合实际的代码。 – 2013-02-23 16:12:54

+0

不用担心。尽管确保示例代码符合特定于语言的样式指南通常是一个好主意,因此人们不会将注意力集中在这个问题上而不是原始问题上^ _ ^ – 2013-02-23 16:18:59

相关问题