title: Simple java message dispatching system
body: <p>I'm working on a little Java game in which all sorts of events can happen.  There are at least a couple of dozen basic events that various event handlers may be interested in.  There are also several places in the code where these events might be triggered.  Rather than forcing the event listeners to know which class they need to register with, I'd like to create some sort of a centralized message-dispatching system, which some classes would submit events into and interested classes could hook into to listen for certain kinds of events.</p>
  
  <p>But I have some questions.  Firstly, this seems like an obvious and common problem.  Are there favorite implementations of simple, in-VM messaging systems?  Seems like there would be.</p>
  
  <p>Secondly, and more importantly, I'm trying to work out a reasonably elegant way for the dispatching class to know as little as possible about types of messages.  I'd love to be able to create new kinds of events without modifying the message dispatcher at all.  However, I have an opposite concern.  I'd really like for the method signatures of the handling methods to be clear.  In other words, I would prefer the following:</p>
  
  <pre><code>public class CollisionConsoleHandler implements CollisionListener {
    @Override
    public void spaceshipCollidedWithMeteor( Spaceship spaceship, Meteor meteor ) {
        //...
    }
  }
  </code></pre>
  
  <p>over something more generic and harder to read:</p>
  
  <pre><code>public class CollisionConsoleHandler implements GameMessageListener {
     @Override
     public void handleMessage( GameMessage message ) {
       if( message instanceof SpaceshipCollisionMessage ) {
          Spaceship spaceship = ((SpaeshipCollisionMessage)message).getSpaceship();
          Meteor meteor = ((SpaeshipCollisionMessage)message).getMeteor();
          //...
       }
     }
  }
  </code></pre>
  
  <p>But I don't see any good ways to keep type-specific knowledge out of the dispatcher while at the same time keeping the method signatures clean and readable.</p>
  
  <p>Ideas?</p>