策略模式进行发送短信

发布时间 2023-12-24 21:28:02作者: 九折丶水平

业务场景

​ 查询数据库的配置表,看配置进行选择不同公司的短信服务

代码

策略代码
// 策略接口
public interface SmsSendStrategy {
    void sendSms(String phone, String template, Map<String,String> map);
}
// 腾讯短信实现策略
@Component
public class TencentSms implements SmsSendStrategy {
    @Override
    public void sendSms(String phone, String template, Map<String, String> map) {
        System.out.println("腾讯发送短信");
    }
}

// 阿里云短信实现策略
@Component
public class AliyunSms implements SmsSendStrategy {

    @Override
    public void sendSms(String phone, String template, Map<String, String> map) {
        System.out.println("阿里云发送短信");
    }
}
调用代码
//接口
public interface SmsService {
    void sendSms(String strategy);
}
//实现层
@Service
public class SmsServiceImpl implements SmsService {
    /**
     * 这个Map的key可以是字符串,这个地方用的枚举就是方便配置的时候知道可以配置哪些值
     *
     * @see StrategyKey
     */
    private final Map<SmsStrategyKey, SmsSendStrategy> sendStrategyMap = new HashMap<>();

    @Autowired
    public SmsServiceImpl(AliyunSms aliyunSms, TencentSms tencentSms) {
        sendStrategyMap.put(SmsStrategyKey.ALIYUN, aliyunSms);
        sendStrategyMap.put(SmsStrategyKey.TENCENT, tencentSms);
    }
//    /**
//     * 引入bean的另一种方式
//     *      这样引入的bean,sendStrategyMap的key是bean的名称
//     */
//    @Autowired
//    private Map<String, SmsSendStrategy> sendStrategyMap;


    /**
     * 根据策略进行短信发送
     *
     * @param strategyName 策略名称,用于找到对应的策略KEY
     */
    @Override
    public void sendSms(String strategyName) {
        //1、查询数据库
        //查询数据库获取strategyName,这个地方是传进来的
        //2、根据策略的名称查询出对应的KEY
        SmsStrategyKey type = SmsStrategyKey.getStrategyKey(strategyName);
        //3、根据key进行查询使用哪个策略
        SmsSendStrategy sendStrategy = sendStrategyMap.get(type);
        if (sendStrategy != null) {
            sendStrategy.sendSms("", "", new HashMap<>());
        } else {
            throw new IllegalArgumentException("未找到对应的策略");
        }
    }
}
其他代码
/**
 * 这个枚举的作用不是特别大
 *      感觉最大的作用就是在数据库知道该配置那些值
 */
public enum SmsStrategyKey {

    ALIYUN("aliyun"),
    TENCENT("tencent");
    private final String name;

    SmsStrategyKey(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static SmsStrategyKey getStrategyKey(String strategyName) {
        for (SmsStrategyKey strategyKey : SmsStrategyKey.values()) {
            if (strategyKey.getName().equalsIgnoreCase(strategyName)) {
                return strategyKey;
            }
        }
       throw new RuntimeException("根据策略名称没有找到对应的KEY");
    }
}
controller
@RestController
public class SmsController {

    @Autowired
    private SmsService smsService;

    @GetMapping("send")
    public String send(String strategyName) {
        smsService.sendSms(strategyName);
        return "success";
    }
}