title: Avoiding type introspection without the Visitor pattern
body: <p>I am looking for OOP design advice for the following fairly trivial problem. I would like to avoid using type introspection (e.g. the Java <code>instanceof</code> operator) without employing the Visitor pattern, which is the typical suggestion. I'm writing this in Java currently, but I think this question is more general than just Java.</p>
  
  <p>Problem background: I am writing a simple collision solver for a physical simulation. I currently have two types of bounding volumes, Axis-aligned bounding boxes (AABBs) and bounding spheres. The simulation contains a collection of objects which may use either type of bounding volume for collision detection. As part of the collision solver I have an "overlap tester" object which simply returns true if the two given bounding volumes intersect. Here is a sketch:</p>
  
  <pre class="lang-java prettyprint-override"><code>interface BoundingVolume {
    ...
  }
  
  class AABB implements BoundingVolume {
    ...
  }
  
  class BoundingSphere implements BoundingVolume {
    ...
  }
  
  class OverlapTester {
    static boolean overlaps(BoundingVolume a, BoundingVolume b) {
      if (a instanceof AABB &amp;&amp; b instanceof AABB) {
        ...
      } else if (a instanceof AABB &amp;&amp; b instanceof BoundingSphere) {
        ...
      } ...
    }
  }
  
  class Simulation {
    List&lt;BoundingVolume&gt; simObjectBVs;
    void collide() {
      for (BoundingVolume a : simObjectBVs) {
        for (BoundingVolume b : simObjectBVs) {
          if (a != b &amp;&amp; OverlapTester.overlaps(a, b)) {
            ...
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>As it is, the <code>overlaps</code> method has a 4-way if-else statement to downcast the parameters to <code>AABB</code>s or <code>BoundingSphere</code>s and call the appropriate overlap method. This is what I would like to avoid.</p>
  
  <p>The typical advice would be to add an <code>overlaps</code> method to each of the <code>AABB</code> and <code>BoundingSphere</code> types which knows how to test itself for overlap with other types of bounding volumes (I think this qualifies as a Visitor pattern). However, I don't think that is the best fit here: upon adding a new type of bounding volume later, I must update each of the other types of bounding volumes to add an overlaps method for the new type. However, if the <code>OverlapTester</code> contained all of this logic, I would only have to add a new method in one place.</p>
  
  <p>Is there another pattern to suit my needs here, or is the Visitor pattern really the best fit?</p>