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
If you are using java 8, you can set up an enum
like this:
enum AnimalFarm {
Meow(Cat::new),
Woof(Dog::new);
public final Supplier factory;
private AnimalFarm(Supplier factory) {
this.factory = requireNonNull(factory);
}
}
......
Animal dog = AnimalFarm.valueOf("Woof").factory.get();
You could even have the enum
implement Supplier
and then do AnimalFarm.valueOf("Meow").get();
.