java if else優化

問題:if else代碼以下圖如何優化json

if (ComponentTypeEnum.bar.name().equals(screenData.getComponentType())) {
    return ResponseUtil.success(barService.get(screenData.getJsonData()));
} else {
    return ResponseUtil.success(yBarService.get(screenData.getJsonData()));
}

優化流程app

第一步:建立工廠方法用於根據條件,生成不一樣的服務類實現ide

public class BarServiceFactory {
    public static BarService getInstance(String type) {
        if (ComponentTypeEnum.bar.name().equals(type)) {
            return SpringContextUtil.getBean(BarServiceImpl.class);
        }else if (ComponentTypeEnum.ybar.name().equals(type)){
            return SpringContextUtil.getBean(YBarServiceImpl.class);
        }
        return null;
    }
}

其中SpringContextUtil代碼以下:優化

@Component
public class SpringContextUtil implements ApplicationContextAware {

    /**
     * 上下文對象實例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 獲取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 經過name獲取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 經過class獲取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 經過name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

第二步:建立一個適配器類,用於匹配工廠方法,產生的不一樣服務類實現,並帶調用具體實現類this

public class BarServiceAdapter implements BarService{
    private BarService barService;

    public BarServiceAdapter(BarService barService){
        this.barService = barService;
    }

    @Override
    public Option get(String json){
        return barService.get(json);
    }
}

第三步:修改對應的表明,已經無需使用if else語句對象

Option option = new BarServiceAdapter(BarServiceFactory.getInstance(screenData.getComponentType())).get(screenData.getJsonData());
return ResponseUtil.success(option);

經過以上優化步驟,由原先4行代碼優化到了2行。條件越多,效果更明顯。哈哈!!!get

相關文章
相關標籤/搜索