title: The best way to implement Factory without if, switch
body: <p>I was looking through many approaches to implement a Factory pattern in Java and still couldn't find a perfect one which doesn't suffer from both if/switch plus doesn't use reflection.
  One of the best that I found was inside Tom Hawtin's answer here: <a href="https://stackoverflow.com/a/3434505/1390874">https://stackoverflow.com/a/3434505/1390874</a></p>
  
  <p>But my biggest concern is that it stores a HashMap of Anonymous classes in a memory.</p>
  
  <p>The question is what do people think about using <strong>Class.newInstance()</strong> in addition to Tom Hawtin's answer?
  This will avoid us from storing unnecessary anonymous classes in memory? Plus code will be more clean.</p>
  
  <p>It will look something like this:</p>
  
  <pre><code>class MyFactory {
      private static final Map&lt;String,Class&gt; factoryMap =
          Collections.unmodifiableMap(new HashMap&lt;String,Class&gt;() {{
              put("Meow", Cat.class);
              put("Woof", Dog.class);
      }});
  
      public Animal createAnimal(String action) {
          return (Animal) factoryMap.get(action).newInstance();
      }
  }
  </code></pre>