I have the following situation: I have to validate a Token using (for now) 2 different strategies, they both do the same thing (check if the token is valid) but in different ways.
My current way of dealing with the strategy instantiation looks like this:
@Service
public class ValidationService {
private Map<ValidationType, ValidationStrategy> validationMap = new HashMap<>();
public ValidationService() {
validationMap.put(ValidationType.A, new AValidationStrategy());
validationMap.put(ValidationType.B, new BValidationStrategy());
}
public void validate(ValidationType type, String token) {
ValidationStrategy strategy = validationMap.get(type);
if(strategy == null) {
strategy = new NoValidationStrategy();
}
strategy.validate(token);
}
}
My question is: Is there a prettier way to set up the proper validation according to the ValidationType enum? Because the constructor would grow more and more as new validation strategies would be added in the system.
I thought that maybe I could keep that Map<> variable and add new Strategy instances when the ValidationService bean would be created by some sort of Spring Boot configuration, but I don't know how I could access the Bean after its instantiation by Spring Boot.
Help me out if you have a better way of doing this! :)
PS: Any code snippets or useful links would be greatly appreciated!