Figure 5.7 The listener pat-
tern. A listener registers
with an event source.
Building a better listener with the whiteboard pattern
A common pattern in many applications is the listener pattern . An event source main-
tains a list of event listeners; when events happen, it notifies each listener in turn.
Interested listeners register and unregister with the event source (see figure 5.7).
What happens when the listener's useful life comes to an end? Depressingly little,
in some cases. Unless the listener is careful, the event source still holds a reference to
the listener. You risk ending up with unused objects hanging around, leaking memory,
and being notified of events that they don't care about and probably can't handle
without throwing an exception. The only way to avoid the issue is to be scrupulously
careful about manually unregistering listeners when they no longer require events.
If you think about it a bit more, you can see that the event source is in fact main-
taining a registry of listeners. It's a pretty simple registry—often nothing more than a
Set or List managed by register() and unregister() methods. Even though the
registries aren't particularly complex, they still need writing. It seems kind of crazy to
re-implement a private registry for every class that could produce events. It seems
extra crazy when even the best-written registries are still prone to memory leaks and
runtime errors from obsolete entries. Less well-written registries can also be crippled
by threading issues.
OUTSOURCING THE REGISTRY
Wouldn't things be better if there were already a registry you could use? One that sup-
ported dependency injection? In OSG i, there is, and it does. Using the Service Registry
as a convenient way of implementing a listener registry is known as the whiteboard pat-
tern (see figure 5.8).
The big advantage of the whiteboard pattern is that it avoids the explicit dependency
between the event source and the listener. The listener merely needs to advertise that
it's interested in events, instead of tracking down a reference to a named event source.
If needed, service properties and filters can be used to ensure listeners are registered
only for events from the right sources; we'll cover more about those in section 6.4.2.
Figure 5.8 The whiteboard pattern. A listener registers with the Service Registry. When an event occurs,
the event source obtains an up-to-date list of listeners to notify from the Service Registry.