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

后端 未结 4 785
攒了一身酷
攒了一身酷 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:06

    Introduce an interface for all tasks and use a factory pattern. The factory can use a map internally. E.g.

    public class TaskFactory {
    
        private Map> taskTypeMap = new HashMap>();
    
        public TaskFactory() {
            taskTypeMap.put("A", ATask.class);
            taskTypeMap.put("B", BTask.class);
        }
    
        public Task createTask(String type) {
            Class taskType = taskTypeMap.get(type);
    
            if (taskType == null) {
                throw new IllegalArgumentException("Task type " + type
                        + " is not supported");
            }
    
            try {
                return taskType.newInstance();
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Unable to instantiate Task of type " + taskType, e);
            }
        }
    
    }
    

    Your client code will then change to

    String type = ...;
    List entityList = ...;
    
    TaskFactory taskFactory = new TaskFactory();
    Task task = taskFactory.createTask(type);
    
    task.performTask();
    
    for (Entity e: entitylist) {
        // do some task
    }
    

提交回复
热议问题