Traveller Pattern

A thought: The Visitor Pattern's match.


In an event based system, there are many objects which have events to be listened to. Sometimes they merely delegate to another object which they are composed of, other times they delegate to a Event Multicaster. Beyond a basic addListener() method (and possibly a removeListener), it's possible that the multicaster contains several methods that may be interesting to a client object, but which will not be available unless they are passed through somehow.

Single-Inheritance is rarely workable. Even ignoring the fact that you may already have to extend some class and therefore can't extend the multicaster, what happens if you want to maintain two discrete subscriptions?

Delegation is often chosen, but it has its drawbacks as well. Delegating every method in the multicaster can be pretty ugly, and exposes a lot of functionality which the client may have no right to (why should the client be able to remove an unrelated listener?). It comes down to the fact that, although useful to the client, it's not the responsibility of the Object to directly provide this access.

There might be a case for the multicaster returning a Visitor of its own (the Traveller). The Traveller could encapsulate, at its simplest, the act of returning/removing the original Visitor. A more complex version could allow the caller to replace the contributed Visitor with a different one. This has several advantages: because the Object only has to pass through the Traveller, a single 'addListener()' type method is now sufficient for most functionality. Secondly, the Traveller safely exposes the client to powerful functionality (replacing the contributed listener, cancelling the listener, etc.), as it grants this access per visitor, and not by multicaster. In some cases, the client may not even need retain a reference to the listener any more.


See original on c2.com