Creating a factory method in Java that doesn't rely on if-else

前端 未结 10 1507
走了就别回头了
走了就别回头了 2020-11-30 23:37

Currently I have a method that acts as a factory based on a given String. For example:

public Animal createAnimal(String action)
{
    if (action.equals(\"M         


        
10条回答
  •  甜味超标
    2020-12-01 00:15

    If you don't have to use Strings, you could use an enum type for the actions, and define an abstract factory method.

    ...
    public enum Action {
        MEOW {
            @Override
            public Animal getAnimal() {
                return new Cat();
            }
        },
    
        WOOF {
            @Override
            public Animal getAnimal() {
                return new Dog();
            }
        };
    
        public abstract Animal getAnimal();
    }
    

    Then you can do things like:

    ...
    Action action = Action.MEOW;
    Animal animal = action.getAnimal();
    ...
    

    It's kind of funky, but it works. This way the compiler will whine if you don't define getAnimal() for every action, and you can't pass in an action that doesn't exist.

提交回复
热议问题