mardi 7 avril 2015

The best way to implement Factory without if, switch

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: http://ift.tt/1c6i71F


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();
}
}

Aucun commentaire:

Enregistrer un commentaire