项目中发短信可能是多渠道的,比如漫道短信、阿里云短信、华为云短信等,不同的客户可能走的不同的渠道,此处可以应用工厂模式。
1.定义发短信的统一接口
public interface ISendSms {
/**
* 发送短信
* @param content
* 短信内容
* @param mobile
* 手机号
* @param cell
* 小号
* @param begin
* 时间
*/
SendResult sendSms(String content, String mobile, String cell, long begin);
}
2.多种渠道去实现,此处忽略不写了。
3.创建工厂类,利用反射
public class SendSmsFactory {
private static Logger LOGGER = LogManager.getLogger(SendSmsFactory.class);
@SuppressWarnings("unchecked")
public <T extends ISendSms> T createFactory(Class<T> c) {
T product = null;
try {
product = (T) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
LOGGER.error("class forName fail", e);
}
return product;
}
}
4.根据不同业务场景,使用工厂发送短信
private static SendResult sendChannelSms(String content, String mobile, String cell, long begin) {
//创建工厂
SendSmsFactory factory = new SendSmsFactory();
ISendSms sendSms = null;
if (StringUtils.isNotBlank(cell)) {//审批
if ("MD".equals(SMS_DEFAULT_APPROVE)) {
sendSms = factory.createFactory(EntinfoSendSms.class);
} else if ("WN".equals(SMS_DEFAULT_APPROVE)) {
sendSms = factory.createFactory(WnSendSms.class);
}
} else {//通知
if ("MD".equals(SMS_DEFAULT_NOTICE)) {//通知
sendSms = factory.createFactory(EntinfoSendSms.class);
} else if ("WN".equals(SMS_DEFAULT_NOTICE)) {
sendSms = factory.createFactory(WnSendSms.class);
}
}
return sendSms.sendSms(content, mobile, cell, begin);
}