title: Generic callback in Java
body: <p>What should be the preferable <code>Java</code> interface or similar pattern that could be used as a <strong>generic callback mechanism</strong>?</p>
  
  <p>For example it could be something like</p>
  
  <pre><code>public interface GenericCallback
  {
      public String getID();
      public void callback(Object notification);
      // or public void callback(String id, Object notification);
  }
  </code></pre>
  
  <p>The ID would be needed for cases of overriden <code>hashCode()</code> methods so that the callee identifies the caller.</p>
  
  <p>A pattern like the above is useful for objects that needs to report back to the class they were spawned from a condition (e.g., end of processing).</p>
  
  <p>In this scenario, the "parent" class would use the <code>getID()</code> method of each of these <code>GenericCallback</code> objects to keep a track of them in a <code>Map&lt;String, GenericCallable&gt;</code> and add or remove them according to the notification received.</p>
  
  <p>Also, how should such an interface be actually named?</p>
  
  <p>Many people seem to prefer the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Observer.html" rel="nofollow">Java Observer pattern</a>, but the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Observable.html" rel="nofollow">Observable class</a> defined there is not convenient, since it not an interface to circumvent single inheritance and it carries more functionality than actually needed in the above, simple scenario.</p>