java 中的策略模式 可以代替大量if else

策略模式是一个非常简单且常用的设计模式,策略模式最常见的作用就是解决代码中冗长的 if-else 或 switch 分支判断语句。 

1、先写一个接口

public interface Strategy {
    /**
     * 发送csv性能数据到redis
     * @param arrList
     */
    void sendPerformanceDataToRedis(List arrList);

    /**
     * 从redis取性能数据转json
     * @param object
     * @return
     */
    Object tranformData(Object object);
}

2、写一个工程,用于注册各个实现类,以及获取实现类方法

@Component
public class StrategyFactory {
    private static Map serviceMap = new ConcurrentHashMap<>();

    public static Strategy getStrategyByName(String name) {
        return serviceMap.get(name);
    }

    public static void register(String name, Strategy strategy) {
        Assert.notNull(strategy, "strategy can't be null");
        serviceMap.put(name, strategy);
    }

}

3、实现类A

@Component
@Slf4j
public class SendFrameRateA implements Strategy, InitializingBean {

    @Override
    public void sendPerformanceDataToRedis(List arrList) {
       // todo
       
    }

    @Override
    public Object tranformData(Object object) {
       // todo
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        StrategyFactory.register("A", this);
    }
}

4、实现类B

@Component
@Slf4j
public class SendFrameRateB implements Strategy, InitializingBean {

    @Override
    public void sendPerformanceDataToRedis(List arrList) {
       // todo
       
    }

    @Override
    public Object tranformData(Object object) {
       // todo
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        StrategyFactory.register("B", this);
    }
}

5、调用

StrategyFactory.getStrategyByName("A").sendPerformanceDataToRedis(arrList);
StrategyFactory.getStrategyByName("B").sendPerformanceDataToRedis(arrList);

你可能感兴趣的:(java,策略模式,开发语言)