← 返回 tesla 的题目列表Event Bus with Emit, Subscribe, and Unsubscribe
类型:qbank
Object-design coding screen: define a listener interface and an event bus class with `emit` and `subscribe`, then support multiple listeners per event and unsubscribe.
Requirements
Define a listener interface.
Implement an EventBus class.
Implement subscribe(event, listener).
Implement emit(event, payload) so subscribed listeners are invoked for the event.
Follow-up: one event can have multiple listeners.
Follow-up: support cancelling a subscription for a specific event.
Notes
Store event -> listeners in a hashmap. Use a set or subscription ID if unsubscribe must be efficient and unambiguous.
Clarify whether listener execution is synchronous or asynchronous, and what happens when one listener throws an exception.
Returning an unsubscribe closure from subscribe is a clean API because callers do not need to retain internal listener-list details.
If ordering matters, preserve insertion order. If concurrency matters, copy the listener list before emitting or guard mutation with a lock.
Preparation
Implement subscribe, emit, and unsubscribe with multiple listeners per event; then refactor subscribe to return a cancellation function or subscription token.
Test listener ordering, duplicate listener registration, unsubscribe during emit, listener exceptions, and emitting an event with no subscribers.
Prepare to discuss sync vs async dispatch and whether one bad listener should stop the remaining listeners.