The best way to implement Factory without if, switch

前端 未结 3 490
青春惊慌失措
青春惊慌失措 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:38

    If you are using java 8, you can set up an enum like this:

    enum AnimalFarm {
        Meow(Cat::new),
        Woof(Dog::new);
    
        public final Supplier factory;
        private AnimalFarm(Supplier factory) {
            this.factory = requireNonNull(factory);
        }
    }
    
    ......
    
    Animal dog = AnimalFarm.valueOf("Woof").factory.get();
    

    You could even have the enum implement Supplier and then do AnimalFarm.valueOf("Meow").get();.

提交回复
热议问题