views:

43

answers:

1

I'm in a situation where I'd like to send a an object out to multiple even handlers, but have certain ones use data produced by other handlers. This sounds pretty unclear - reading it myself I don't think I'd get what I was talking about - so I'll give an example.

Let's say I've got the following:

interface ChangeListener
{
   public add_change(Change)
   // ...
}

class ListenerA implements ChangeListener{...}
class ListenerB implements ChangeListener{...}

and where the actual logic is taking place:

List changes = ... // populated from somewhere else
List handlers = [new ListenerA(), new ListenerB()]

foreach(change in changes)
  foreach(handler in handlers)
    handler.add_change(change)

My problem is that part of what ListenerA will do is create a URL for the change, and I'd like ListenerB to have access to that URL (so it can use it). As a specific example, ListenerA could use a blogging API to create a post on the change, and ListenerB could then send an email with that URL.

One option would be to have ListenerA add a property to the Change object with the newly-created URL, but I'm not sure I like mucking about with the object. Another would be to simply call them in order and pass in a value (as opposed to looping through them), but I'm trying to keep a clean separation of concerns between this part (which sends out the changes) and the listeners who try and figure out how to deal with them - so that in the future all it would take to add a ListenerC would be adding an object to the handlers list.

Any ideas on a best approach?

+1  A: 

Sounds like what you want is Listener B to be listening to Listener A instead of having both listening to the same object. Basically it would be a chain. Object changes and tells it's listeners (Listener A). Listener A changes and tells it's listeners (Listener B).

Since B has a dependency on A that is where B should be listening.

Rob Booth