zoukankan      html  css  js  c++  java
  • 策略模式的应用

    实现案例选择不同的通道发送短信,基于springboot实现。

    SmsService接口,定义了两个方法,发送短信和选择通道。

    public interface SmsService {
        //有两种发送通道
        /**
         * 发短信
         */
        void sendSms();
    
        /**
         * 选择发送通道
         * @return
         */
        SmsType smsType();
    }

    两个实现类,代表了两种发送短信的通道。

    @Service
    public class AliYunSmsServiceImpl implements SmsService {
        @Override
        public void sendSms() {
            System.out.println("阿里云发送信息");
        }
    
        @Override
        public SmsType smsType() {
            return SmsType.ALIIYUN;
        }
    }
    @Service
    public class PingAnYunSmsServiceImpl implements SmsService {
        @Override
        public void sendSms() {
            System.out.println("平安云发送信息");
        }
    
        @Override
        public SmsType smsType() {
            return SmsType.PINGANYUN;
        }
    }
    public enum SmsType {
        ALIIYUN,PINGANYUN
    }

    策略模式的关键类,在项目启动时,初始化bean保存到map中。

    @Component
    public class StrategyModel implements ApplicationContextAware {
        private ApplicationContext applicationContext;
        Map<SmsType,SmsService> mapStrategy = new ConcurrentHashMap<>();
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                this.applicationContext = applicationContext;
        }
    
        @PostConstruct
        public void initMap(){
            Map<String, SmsService> beansOfType = applicationContext.getBeansOfType(SmsService.class);
            beansOfType.forEach((k,v)->{
                //将bean保存到map中
                mapStrategy.put(v.smsType(),v);
            });
        }
    
        public SmsService strategy(SmsType smsType){
            return mapStrategy.get(smsType);
        }
    }

    config类,配置扫描路径,用于单元测试。

    @Configuration
    @ComponentScan("com.moon.springprojectstrategy")
    public class Config {
    }

    测试类:

    @SpringBootTest
    class SpringprojectstrategyApplicationTests {
    
        @Test
        void contextLoads() {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
            StrategyModel strategyModel = applicationContext.getBean(StrategyModel.class);
            SmsService smsService1 = strategyModel.strategy(SmsType.PINGANYUN);
            smsService1.sendSms();
            SmsService smsService2 = strategyModel.strategy(SmsType.ALIIYUN);
            smsService2.sendSms();
        }
    
    }

    运行结果:

  • 相关阅读:
    【分享】管理的最高境界是简单
    建立市场化风险评估机制推进地方政府信用评级建设
    手游-神雕侠侣 85侠客纪攻略(已通关)
    使用git的分支功能实现定制功能摘取与组合的想法
    组内正则培训记录
    组内Linq培训记录
    一次代码重构记录
    git代码库误操作还原记录
    关于代码重构的开始
    如何管理高手、大牛?
  • 原文地址:https://www.cnblogs.com/menbo/p/13991938.html
Copyright © 2011-2022 走看看