I think the native implementation of the Observer Java pattern is not suitable for your case.
In fact, the general Observer pattern can be used when only one Observed event type can occur. In the observer design pattern, all Observes is always notified.
So, in this case, you need to expand the general Observer template by defining your own Observable interface, for example, as follows:
public enum EventKind { EVENT_A, EVENT_B, EVENT_C; } public interface Observable { public void registerObserver(EventKind eventKind); public void unregisterObserver(EventKind eventKind); public void notifyObservers(EventKind eventKind); }
Then you can simply implement this Observable interface with internal lists to notify each type of event. You can use the built-in Observer interface if you want.
This approach has the following advantages:
- You can flexibly add more events without affecting the Observers code.
- You can register any observer in any event.
- You only update observers who are effectively interested in each event.
- You avoid "empty methods", "event type checking" and other tricks on the observer side.
source share