title: Which design pattern allows abstraction of functionality based on runtime types?
body: <p>I have an abstract class A and several implementations of it. I expect this to  evolve over time, by adding more implementations.</p>
  
  <p>I also have an interface that does something at instances of the above class hierarchy (eg print them).</p>
  
  <p>I want implementations of the interface to provide some special functionality for some of the subclasses of A and a default functionality for the rest of them.</p>
  
  <p>I hope this example clarifies things:</p>
  
  <pre><code>abstract class A { }
  class B extends A { }
  class C extends A { }
  
  interface Processor  {
      public void process(A a);
  }
  
  class SimpleProcessor implements Processor {
  
      //I want this to be called when argument is instance of A or C or any
      //new class that will be added in the future
      public void process(A a) {
          //Line 14
          System.out.println("Default processing");
      }
  
      //I want this to be called when argument is instance of B
      public void process(B b) {
          System.out.println("Special processing");
      }
  
  }
  
  public class Runner {
  
      public static void main(String[] args) {
          B b = new B();
          Processor p = new SimpleProcessor();
          p.process(b);
      }
  
  }
  </code></pre>
  
  <p>The example prints "Default processing". The problem is that the method to be executed is chosen based at the compile-time type of the interface's method. Is there a way (or design pattern) to make this program print "Special processing" without adding at line 14 a list of </p>
  
  <pre><code>if (a instance of B)
    process( (B) a );
  </code></pre>
  
  <p>for every class that needs special processing?</p>
  
  <p>I had a look at the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">visitor</a> pattern but it doesn't seem like an improvement because I don't want to "pollute" the Processor interface with methods for every subclass of A because more subclasses of A will be added.</p>
  
  <p>To put it another way, I want the implementations of the interface to:</p>
  
  <ul>
  <li>provide custom implementation of the method for specific subclasses of A</li>
  <li>provide a default implementation for classes that will be added in the future</li>
  <li>avoid listing all the classes in a large if-then-else list</li>
  </ul>
  
  <p>Thanks!!</p>