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: https://mcmap.net/q/49051/-creating-a-factory-method-in-java-that-doesn-39-t-rely-on-if-else
But my biggest concern is that it stores a HashMap of Anonymous classes in a memory.
The question is what do people think about using Class.newInstance() in addition to Tom Hawtin's answer? This will avoid us from storing unnecessary anonymous classes in memory? Plus code will be more clean.
It will look something like this:
class MyFactory {
private static final Map<String,Class> factoryMap =
Collections.unmodifiableMap(new HashMap<String,Class>() {{
put("Meow", Cat.class);
put("Woof", Dog.class);
}});
public Animal createAnimal(String action) {
return (Animal) factoryMap.get(action).newInstance();
}
}