22
22
import com .google .common .annotations .VisibleForTesting ;
23
23
import java .util .List ;
24
24
import org .apache .gravitino .exceptions .ForbiddenException ;
25
+ import org .apache .gravitino .listener .api .EventDispatcher ;
25
26
import org .apache .gravitino .listener .api .EventListenerPlugin ;
26
27
import org .apache .gravitino .listener .api .event .BaseEvent ;
27
28
import org .apache .gravitino .listener .api .event .Event ;
@@ -38,6 +39,7 @@ public class EventBus {
38
39
// which are meant for synchronous event listening, or AsyncQueueListener, designed for
39
40
// asynchronous event processing.
40
41
private final List <EventListenerPlugin > eventListeners ;
42
+ private final InternalVisitor internalVisitor ;
41
43
42
44
/**
43
45
* Constructs an EventBus with a predefined list of event listeners.
@@ -47,6 +49,7 @@ public class EventBus {
47
49
*/
48
50
public EventBus (List <EventListenerPlugin > eventListeners ) {
49
51
this .eventListeners = eventListeners ;
52
+ this .internalVisitor = new InternalVisitor ();
50
53
}
51
54
52
55
/**
@@ -56,13 +59,7 @@ public EventBus(List<EventListenerPlugin> eventListeners) {
56
59
* @param baseEvent The event to be dispatched to all registered listeners.
57
60
*/
58
61
public void dispatchEvent (BaseEvent baseEvent ) {
59
- if (baseEvent instanceof PreEvent ) {
60
- dispatchPreEvent ((PreEvent ) baseEvent );
61
- } else if (baseEvent instanceof Event ) {
62
- dispatchPostEvent ((Event ) baseEvent );
63
- } else {
64
- throw new RuntimeException ("Unknown event type:" + baseEvent .getClass ().getSimpleName ());
65
- }
62
+ baseEvent .accept (internalVisitor );
66
63
}
67
64
68
65
/**
@@ -77,11 +74,18 @@ List<EventListenerPlugin> getEventListeners() {
77
74
return eventListeners ;
78
75
}
79
76
80
- private void dispatchPostEvent (Event postEvent ) {
81
- eventListeners .forEach (eventListener -> eventListener .onPostEvent (postEvent ));
82
- }
77
+ /** Internal visitor is an inner private class that dispatches events to registered listeners. */
78
+ private class InternalVisitor implements EventDispatcher {
79
+ /** {@inheritDoc} */
80
+ @ Override
81
+ public void dispatchPreEvent (PreEvent event ) throws ForbiddenException {
82
+ eventListeners .forEach (eventListener -> eventListener .onPreEvent (event ));
83
+ }
83
84
84
- private void dispatchPreEvent (PreEvent preEvent ) throws ForbiddenException {
85
- eventListeners .forEach (eventListener -> eventListener .onPreEvent (preEvent ));
85
+ /** {@inheritDoc} */
86
+ @ Override
87
+ public void dispatchPostEvent (Event event ) {
88
+ eventListeners .forEach (eventListener -> eventListener .onPostEvent (event ));
89
+ }
86
90
}
87
91
}
0 commit comments