策略模式的简单实例

spring应用上下文 + spring bean生命周期

public class StrategyTest {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/config/applicationContext.xml");
        StrategyLoader strategyLoader = applicationContext.getBean(StrategyLoader.class);
        String result = strategyLoader.getStrategyInfo("策略一");
        System.out.println(result);

    }
}

class StrategyLoader implements InitializingBean, ApplicationContextAware{
    private ApplicationContext applicationContext;
    private static Map strategyInfoMap = new HashMap();

    public void afterPropertiesSet() throws Exception {
        Map strategyInfos = applicationContext.getBeansOfType(StrategyInfo.class);
        if(CollectionUtils.isEmpty(strategyInfos)) {
            return;
        }

        for(String key : strategyInfos.keySet()) {
            strategyInfoMap.put(strategyInfos.get(key).getIdentify(), strategyInfos.get(key));
        }
    }

    public String getStrategyInfo(String strategy){
        StrategyInfo strategyInfo = strategyInfoMap.get(strategy);
        if(strategyInfo != null) {
            return strategyInfo.getStrategyInfo(strategy);
        }
        return "";
    }

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

interface StrategyInfo {
    String getStrategyInfo(String strategy);
    String getIdentify();
}

class Strategy1 implements StrategyInfo {

    private static final String identify = "策略一";

    public String getStrategyInfo(String strategy) {
        return "策略一 " + strategy;
    }

    public String getIdentify(){
        return identify;
    }
}

class Strategy2 implements StrategyInfo {

    private static final String identify = "策略一";
    public String getStrategyInfo(String strategy) {
        return "策略二 " + strategy;
    }

    public String getIdentify(){
        return identify;
    }
}

参考链接:https://segmentfault.com/a/1190000005844400

如有侵权,请联系删除

你可能感兴趣的:(java,设计模式)