samedi 26 octobre 2019

how solve if cascade\case-of in a factory pattern

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 manage 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 code smell. The problem is the "case-of" that I have to write 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 class.

My question is: there is a way to avoid this situation? There is a pattern that allows me to create an object based to another paremeter without have "cascade-if\case-of" like that?

I was thinking to use the command pattern but at the end I still have this situation.

Aucun commentaire:

Enregistrer un commentaire