You basically implement the Factory pattern as suggested in other answers. But in the end, you will have to write an βifβ or βswitchβ statement to choose to fix the implementation (or strategy) for your enum value. But, as you already mentioned, you will have to expand this selection template whenever you add or remove an enumeration value. You can get around this using a map like this:
public class ProcessorSelector { private final Map<VehicleType, ObjectProcessor> processors; public ProcessorSelector(Map<VehicleType, ObjectProcessor> processors) { this.processors = processors; } public void process(VehicleType type, List<String> input) { processors.get(type).process(input); } }
You cannot configure your ProcessorSelector by passing a map with all processor implementations mapped to the correct enumeration value (note that I used guava ImmutableMap to conveniently build a hash map:
new ProcessorSelector(ImmutableMap.of( VehicleType.CAR, new CarImpl(), VehicleType.VAN, new VanImpl());
You no longer have to change your ProcessorSelector, only the construction / configuration of the class. In fact, you could say that we just implemented a strategy diagram here. These selector classes are very common, and if you feel that you implement them quite often, you can even use a more general implementation, I recently described this on the blog: https://hansnuttin.wordpress.com/2015/12/03/functionselector/
Hans nuttin
source share