接口定义
public interface SmsService {
void send(String content);
public SmsType smsType();
}
短信通道
public enum SmsType {
ALIYUN,
MOBILE
}
接口实现
public class AliyunSmsService implements SmsService {
@Override
public void send(String content) {
System.out.println("阿里云发送短信。。。。。。。。。");
}
@Override
public SmsType smsType() {
return SmsType.ALIYUN;
}
}
public class MoblieSmsService implements SmsService {
@Override
public void send(String content) {
System.out.println("中国移动发送短信...........");
}
@Override
public SmsType smsType() {
return SmsType.MOBILE;
}
}
短信通道管理
public class SMSstrategy implements ApplicationContextAware {
private static Map<SmsType, SmsService> serviceMap = new ConcurrentHashMap<>();
private ApplicationContext applicationContext;
public SmsService getService(SmsType smsType) {
return serviceMap.get(smsType);
}
@PostConstruct
public void initSMService() {
Map<String, SmsService> beansMap = applicationContext.getBeansOfType(SmsService.class);
beansMap.forEach((String t, SmsService service) -> {
serviceMap.put(service.smsType(), service);
});
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
接口调用
public static void doSend(String[] args) {
SMSstrategy smSstrateg = new SMSstrategy();
SmsService aliyunService = smSstrateg.getService(SmsType.ALIYUN);
aliyunService.send("hello,world");
SmsService mobileService = smSstrateg.getService(SmsType.MOBILE);
mobileService.send("hello,world2");
}