我正在尝试编写一个自定义事件。我读到我应该有 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/