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 u
Try something like this:
class MyFactory {
private static final Map> factoryMap =
Collections.unmodifiableMap(new HashMap() {
put("Meow", Cat.BASE_INSTANCE);
put("Woof", Dog.BASE_INSTANCE);
});
public Animal createAnimal(String action) {
return factoryMap.get(action).instance();
}
}
interface Animal {
public SELF instance();
}
class Cat implements Animal {
public static final Cat BASE_INSTANCE = new Cat();
public Cat() {}
public Cat instance(){
return new Cat();
}
}
// And a similar Dog class
This does not use reflection, if, or switch, at all.