While refactoring some code, I found that we should use some polymorphism in several places, instead of having a bunch of if / else blocks all over the place.
While object-oriented classes were very easy to create, the problem arises when we have to decide which implementation to use. There seem to be a lot of solutions, but I would like to see if there are any more elegant or โbetterโ ways to do this.
So essentially, let's say, for the sake of example, I'm going to choose a credit card and for each type of credit card, I have an implementation. So I have a class structure like this:
Each of the child classes extends the class of the CreditCard class.
Now in the web application, I will pass a line representing the type of map that the user has selected. Now I need to direct this to the implementing class itself. This is where a lot of options begin.
Please let me know if there are any better options, or if I am stuck with them.
Factory
@Autowired @Qualifier("visa") private CreditCard visa;
@Autowired @Qualifier("mastercard") private CreditCard mastercard;
@Autowired @Qualifier("amex") private CreditCard amex;
public CreditCard getCreditCard(String input) {
{
if ("visa".equals(input)) {
return visa;
} else if ("mastercard".equals(input)) {
return mastercard;
} else if ("amex".equals(input)) {
return amex;
}
return null;
}
Map
@Autowired HashMap<String, CreditCard> creditCardImpls;
public CreditCard getCreditCard(String input) {
return creditCardImpls.get(input);
}
ApplicationContext getBean :
@Autowired private ApplicationContext applicationContext;
public CreditCard getCreditCard(String input) {
return applicationContext.getBean(input);
}
The problem that I see here is that with the help of the factory I will need to auto-increase potentially several different fields if we are going to add many more types of credit cards in the future. Then the problem with the Map is that we are not using Spring to capture the bean. For t it is getBean from ApplicationContext, we do not follow the IoC that Spring provides.
?