title: Polymorphic factory / getInstance() in Java
body: <p>I'm aiming to create a set of objects, each of which has a unique identifier. If an object already exists with that identifier, I want to use the existing object. Otherwise I want to create a new one. I'm trying not to use the word Singleton, because I know it's a dirty word here...</p>
  
  <p>I can use a factory method:</p>
  
  <pre><code>    // A map of existing nodes, for getInstance.
  private static Map&lt;String, MyClass&gt; directory = new HashMap&lt;String, MyClass&gt;();
  
  public static MyClass getInstance(String name) {
      MyClass node = directory.get(name);
      if(node == null) {
         node == new MyClass(name);
      }
      return node;
  }
  </code></pre>
  
  <p>Or equally, I could have a separate MyClassFactory method.</p>
  
  <p>But I had intended to subclass MyClass:</p>
  
  <pre><code>public class MySubClass extends MyClass;
  </code></pre>
  
  <p>If I do no more, and invoke MySubClass.getInstance():</p>
  
  <pre><code>MyClass subclassObj = MySubClass.getInstance("new name");
  </code></pre>
  
  <p>... then subclassObj will be a plain MyClass, not a MySubClass.</p>
  
  <p>Yet overriding getInstance() in every subclass seems hacky.</p>
  
  <p>Is there a neat solution I'm missing?</p>
  
  <hr>
  
  <p>That's the generalised version of the question. More specifics, since the answerers asked for them.</p>
  
  <p>The program is for generating a directed graph of dependencies between nodes representing pieces of software. Subclasses include Java programs, Web Services, Stored SQL procedures, message-driven triggers, etc.</p>
  
  <p>So each class "is-a" element in this network, and has methods to navigate and modify dependency relationships with other nodes. The difference between the subclasses will be the implementation of the <code>populate()</code> method used to set up the object from the appropriate source.</p>
  
  <p>Let's say the node named 'login.java' learns that it has a dependency on 'checkpasswd.sqlpl':</p>
  
  <pre><code>this.addDependency( NodeFactory.getInstance("checkpasswd.sqlpl"));
  </code></pre>
  
  <p>The issue is that the checkpasswd.sqlpl object may or may not already exist at this time.</p>