The best way to implement Factory without if, switch

前端 未结 3 512
青春惊慌失措
青春惊慌失措 2021-01-12 17:13

I was looking through many approaches to implement a Factory pattern in Java and still couldn\'t find a perfect one which doesn\'t suffer from both if/switch plus doesn\'t u

3条回答
  •  遥遥无期
    2021-01-12 17:18

    Try something like this:

    class MyFactory {
        private static final Map> factoryMap =
            Collections.unmodifiableMap(new HashMap() {
                put("Meow", Cat.BASE_INSTANCE);
                put("Woof", Dog.BASE_INSTANCE);
        });
    
        public Animal createAnimal(String action) {
            return factoryMap.get(action).instance();
        }
    }
    
    interface Animal {
        public SELF instance();
    }
    
    class Cat implements Animal {
        public static final Cat BASE_INSTANCE = new Cat();
        public Cat() {}
        public Cat instance(){
            return new Cat();
        }
    }
    // And a similar Dog class
    

    This does not use reflection, if, or switch, at all.

提交回复
热议问题