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。其他 UI 将使用相同的界面,但主体会有所不同。

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

4

2 回答 2

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

  }

}
于 2013-02-23T16:02:26.767 回答
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()”会。

于 2013-02-23T16:07:35.570 回答