策略模式的应用

实现案例选择不同的通道发送短信,基于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();
    }

}

运行结果:

原文地址:https://www.cnblogs.com/menbo/p/13991938.html