title: dispatch design pattern?
body: <p>Suppose I have a class hierarchy in Java:</p>
  
  <pre><code>interface Item { ... };
  class MusicBox implements Item { ... };
  class TypeWriter implements Item { ... };
  class SoccerBall implements Item { ... };
  </code></pre>
  
  <p>and I have another class in the same package:</p>
  
  <pre><code>class SpecialItemProcessor {
      public void add(Item item)
      {
          /* X */
      }
  }
  </code></pre>
  
  <p>where I want to do something different for each item type, but I don't want to define that action in the different <code>Item</code> classes (<code>MusicBox</code>, <code>TypeWriter</code>, <code>SoccerBall</code>).</p>
  
  <p>One way to handle this is:</p>
  
  <pre><code>class SpecialItemProcessor {
      public void add(Item item)
      {
          if (item instanceof MusicBox)
          {
              MusicBox musicbox = (MusicBox)item;
              ... do something ...
          }
          else if (item instanceof MusicBox)
          {
              TypeWriter typewriter = (TypeWriter)item;
              ... do something ...
          }
          else if (item instanceof SoccerBall)
          {
              SoccerBall soccerball = (SoccerBall)item;
              ... do something ...
          }
          else
          {
              ... do something by default ...
          }
      }
  }
  </code></pre>
  
  <p>This works but it seems really clunky. <strong>Is there a better way to do this, when I know of special cases?</strong> (obviously if <code>Item</code> contains a method <code>doSomethingSpecial</code> then I can just call that item's method without caring what type it is, but if I don't want that differentiation to occur within the item itself how do I deal with it?)</p>