Which Java Design Pattern fits best for if-else statement including loop?

后端 未结 4 788
攒了一身酷
攒了一身酷 2021-01-24 04:55

I have a use case with 7-8 if else. Sample use case:

 String type;
 List < Entity > entityList;


 if (type.equals(\"A\")) {
    ClassA a = new ClassA();
          


        
4条回答
  •  悲哀的现实
    2021-01-24 05:02

    A factory implementation could look like this:

    public class WidgetFactory {
        public static void main(String[] args) {
            String type = "A";
            List entityList = new ArrayList<>();
    
            Widget widget = WidgetFactory.createWidget(type);
            widget.performTask();
            for (Entity e : entityList) {
                widget.performTaskOnEntity(e);
            }
        }
    
        private static Widget createWidget(String type) {
            switch (type) {
                case "A":
                    return new ClassA();
                case "B":
                    return new ClassB();
                default:
                    throw new IllegalArgumentException("Unknown type: " + type);
            }
        }
    
        private interface Widget {
            void performTask();
            void performTaskOnEntity(Entity entity);
        }
    
        private static class ClassA implements Widget {
            public void performTask() { }
            public void performTaskOnEntity(Entity entity) { }
        }
    
        private static class ClassB implements Widget {
            public void performTask() { }
            public void performTaskOnEntity(Entity entity) { }
        }
    
        private static class Entity {
        }
    }
    

提交回复
热议问题