springboot 策略+工厂模式优化if..else..

1.策略接口

public interface IStrategy {

    /**
     * 根据id获取对应数据
     * @param dispatchQuery
     */
     T getData(QueryParams queryParams);
}

2. 策略工厂

@Component
public class StrategyFactory {
    /**
     * 关键功能 Spring 会自动将 EntStrategy 接口的类注入到这个Map中
     */

    @Autowired
    private Map strategies = new ConcurrentHashMap<>();

    public IStrategy getStrategy(String graphId){
        IStrategy strategy = strategies.get(graphId);
        if(null == strategy) {
            throw new BizException(ResultEnum.STRATEGY_NOT_EXITS);
        }

        return strategy;
    }
}

这里的strategies map用@Autowired修饰, spring IOC会自动将实现Istragety的类put到该map中,这里就是本文的关键,你品,细品!建议看相关源码搞清楚

3.具体的策略类

@Component("one")
public class OneStrategy implements IStrategy {
 //TODO
}

这时候的OnStrategy已然在上文中的map中

4.上下文

@Component
public class DispatchCtx {

    @Autowired
    private StrategyFactory strategyFactory;

    public  T getData(DispatchQuery dispatchQuery) {
        if (StringUtils.isEmpty(dispatchQuery)) {
            throw new BizException(ResultEnum.STRATEGY_NOT_EXITS);
        }

        IStrategy strategy = strategyFactory.getStrategy(dispatchQuery.getGraphId());
        return strategy.getGraphData(dispatchQuery);
    }

}

5.替换原来的if...else...

 for (String id: graphIds) {
            QueryParams query = QueryParams();
            query .setStrategyId(id);
            Map graphMap = dispatchCtx.getGraphData(query );
            list.add((T) graphMap);
        }

总结:该实现主要运用了java泛型及工厂+策略模式,摆脱了原来的if...else...的逻辑判断的堆砌。

你可能感兴趣的:(springboot)