采用工厂+策略模式消除if-else

采用工厂+策略模式消除if-else

创建工厂类

public class TestStrategyFactory {

    private static Map<OperationType, OperationMethodStrategy> strategyMap = new ConcurrentHashMap<>();

    public static <T extends OperationMethodStrategy> T getOperationService(OperationType type) {
        return (T) strategyMap.get(type);
    }

    @Autowired
    public TestStrategyFactory(List<OperationMethodStrategy> list) {
        for (OperationMethodStrategy strategy : list) {
            strategyMap.putIfAbsent(strategy.getType(), strategy);
        }
        log.info("TestStrategy strategyMap {}", strategyMap);
    }
}

创建策略接口

public interface OperationMethodStrategy {

    void operationMethod(String message, SystemSourceTypeEnum sourceType, String url);

    OperationType getType();
}

结果

        OperationMethodStrategy methodStrategy = TestStrategyFactory.getOperationService(OperationType.enumOf(dto.getNoun()));
        if (methodStrategy == null) {
            throw new IllegalArgumentException("Operation is not exist");
        }
        methodStrategy.operationMethod(message, sourceType, dto.getUrl());

注意
对应的实现类需要由spring容器管理
采用工厂+策略模式消除if-else_第1张图片

你可能感兴趣的:(日常学习,java)