java - 编写自定义事件的监听器接口(interface)

标签 java events interface custom-events

我正在尝试编写一个自定义事件。我读到我应该有 3 个东西:1.组件类、2.事件类和 3.监听器接口(interface)。

我的问题是我必须在一个类中创建一组监听器,如下所示:

public class MyEvent{
     private Set<EventListener> = new HashSet<>();
        public synchronized void addListener(EventListener listener){
        listeners.add(listener);
     }

      //and the rest of the code for firing event .. 

}

这是界面:

 public interface EventListener {
      void hungry(MyEvent event);
 }

我不明白拥有一组接口(interface)意味着什么?

最佳答案

这里 Set 的每个元素都是事件的监听器:

 private Set<EventListener> = new HashSet<>();

在您的设计中,多个订阅者似乎可以订阅同一事件的通知。
例如,假设您有一个事件:“应用程序已启动”。多个对象可能想要知道此通知事件。

请注意,事件通常不存储监听器(或观察者)。组件(或可观察对象)的作用是存储它们。您还应该提供一种通知听众的方法。例如:

public class MyComponent{
     private Set<EventListener> listeners = new HashSet<>();

     public synchronized void addListener(EventListener listener){
        listeners.add(listener);
     }

     public void notify(MyEvent myEvent){
        listeners.stream().forEach(e->e.hungry(myEvent));
     }
}

你可以这样设置对象之间的关系:

MyComponent component = new MyComponent();
EventListener fooListener = new EventListenerImpl(...);
EventListener barListener = new EventListenerImpl(...);
component.addListener(fooListener);
component.addListener(barListener);
// trigger the event
component.notify(new HugryEvent());

关于java - 编写自定义事件的监听器接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346722/

相关文章:

java - 使用 -D 将参数传递给 java 二进制文件时使用 '.' 不能很好地解析

cocoa /碳 : catch global hotkey when key is kept pressed (held down)

c++ - 面对非阻塞I/O,如何设计状态机?

android - 类和 Activity 通过接口(interface)进行通信

c++ - 我们是继承接口(interface)还是实现接口(interface)?

java - 何时取消引用 java web mvc 中的对象

java - HashMap 中公共(public)值的返回键

java - Hibernate 中同一个表中的一对多映射

javascript - Wijmo 的 valueChanged 事件 + Angular 2 上的数据绑定(bind)问题

Java实现两个接口(interface)并解决默认方法冲突 : why using super keyword?