I have to create an object based on a specific situation. I read, that the solution could be the Factory Pattern, but in my case it has a lot of disadvantages.
For instance: I have an application that manages animals. At some point a client gives to me a list of animals that must be created. A solution by using the factory pattern should be:
//PRODUCTS
public interface Animal {
String getCall();
}
public class Dog implements Animal {
public String getCall() {
return "Bau";
}
}
public class Cat implements Animal {
public String getCall() {
return "Miao";
}
}
public class Cow {...}
public class Rooster{...}
public enum AnimalEnum {
Cat, Dog, Cow, Rooster
}
//FACTORY
public class AnimalFactory {
public Animal getAnimal (AnimalEnum type){
Animal retval = null;
switch (type){
case Cat:
retval = new Cat();
break;
case Dog:
retval = new Dog();
break;
case Cow:[...]
case Rooster[...]
}
return retval;
}
}
In my opinion this is a code smell. The problem is the case-statement that I have to write in order to check what type of animal the client wants. Furthermore, if in the future I want to create a new object "Tiger", I have to change all the factory classes.
My question is: is there a way to avoid this situation? Is there a pattern that allows me to create an object based on another parameter without having "cascading if\case-of" like that?
I was thinking, to use the command pattern, but at the end I still have this situation.