说明问题之前,我们先来看一个小的demo:

首先创建一个简单springboot web 项目, 主要代码如下:

新建一个接口 实现 process 功能

public interface Strategy {

    void process(Object o);
}

添加 process 功能 的三种不同实现方式

@Component("PLAN_A")
public class StrategyImplA implements Strategy {
    @Override
    public void process(Object o) {
        System.out.println("StrategyImplA");
    }
}
@Component("PLAN_B")
public class StrategyImplB implements Strategy {
    @Override
    public void process(Object o) {
        System.out.println("StrategyImplB");
    }
}
@Component("PLAN_C")
public class StrategyImplC implements Strategy {
    @Override
    public void process(Object o) {
        System.out.println("StrategyImplB");
    }
}

StrategyContext 中可以通过实现 afterPropertiesSet() 方法,看到属性已被注入。其中 strategyMap中key 为属性的名称,value为 具体实现。所以,我们就可以通过这个方式 来实现策略方案了。是不是很惊艳!!!!!

再来一个 补充的地方,就是如果 我们获取具体方法策略的时候,没有获取到具体策略 怎么办呢?这个时候 我们就想到了线程池的拒绝策略实现,如果找不到就给一种默认的策略实现。

调整后的实现如下:

@Component
public class StrategyContext implements InitializingBean, ApplicationContextAware {

    private static Strategy DEFAULT_STRATEGY = new DefaultStrategy();
    private ApplicationContext applicationContext;
    @Resource
    private Map<String, Strategy> STRATEGY_MAP = new HashMap<>(4);

    @Override
    public void afterPropertiesSet() throws Exception {

        STRATEGY_MAP = applicationContext.getBeansOfType(Strategy.class);
    }

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


    public Strategy getStrategy(String strategyName) {
        return STRATEGY_MAP.get(strategyName) == null ? DEFAULT_STRATEGY : STRATEGY_MAP.get(strategyName);
    }

    static class DefaultStrategy implements Strategy {
        @Override
        public void process(Object o) {
            System.out.println("default PLAN");
        }
    }
}

这种就是为了防止 调用方 没有获取到对应的处理策略 出现空指针异常,或者其他不可控的行为。

测试

@SpringBootTest
class StrategyBootApplicationTests {

    @Autowired
    StrategyContext strategyContext;

    @Test
    void contextLoads() {

        Strategy strategy = strategyContext.getStrategy("PLAN_A");
        strategy.process(1L);


        strategy = strategyContext.getStrategy("PLAN_E");
        strategy.process(2L);
    }
}
输出
StrategyImplA
default PLAN

https://github.com/andanyoung/springboot/tree/master/strategy-boot

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐