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

前端 未结 10 1468
走了就别回头了
走了就别回头了 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-11-30 23:55

    Now you could use Java 8 constructor references and a functional interface.

    import java.util.HashMap;
    import java.util.Map;
    import java.util.function.Supplier;
    
    public class AnimalFactory {
        static final Map> constructorRefMap = new HashMap<>();
    
        public static void main(String[] args) {
            register("Meow", Cat::new);
            register("Woof", Dog::new);
    
            Animal a = createAnimal("Meow");
            System.out.println(a.whatAmI());
        }
    
        public static void register(String action, Supplier constructorRef) {
            constructorRefMap.put(action, constructorRef);
        }
    
        public static Animal createAnimal(String action) {
            return constructorRefMap.get(action).get();
        }
    }
    
    interface Animal {
        public String whatAmI();
    }
    
    class Dog implements Animal {
        @Override
        public String whatAmI() {
            return "I'm a dog";
        }
    }
    
    class Cat implements Animal {
        @Override
        public String whatAmI() {
            return "I'm a cat";
        }
    }
    

提交回复
热议问题