前言
工厂模式的应用场景是需要创建一组同类型或类似的对象,编码时无法预见需要创建哪种类的实例
这里以发送短信为例,根据不同的业务可能需要使用不同的短信厂商来发送短信,只需传入对应的厂商标识即可使用对应的厂商短信能力,并且便于扩展接入新的短信厂商
一、短信工厂类
用于管理以及根据类型获取对应的短信实例
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
*
* 短信工厂类
*/
@Component
public class SmsFactory implements ApplicationContextAware {
//短信实例map
public static Map<String, SmsService> connectionMap = new HashMap<String, SmsService>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//根据接口类型返回相应的所有bean
Map<String, SmsService> map = applicationContext.getBeansOfType(SmsService.class);
for (Map.Entry<String, SmsService> data : map.entrySet()) {
String smsType = data.getValue().getSmsType();
if (StrUtil.isNotBlank(smsType)) {
connectionMap.put(smsType, data.getValue());
}
}
}
public static SmsService getSmsService(String smsTyoe) {
//根据唯一标识获取对应实例
SmsService smsService = connectionMap.get(smsTyoe);
if (Objects.nonNull(smsService)) {
return smsService;
} else {
throw new ServiceException("短信厂商类型不正确!!");
}
}
}
二、短信通用接口类
该类定义了短信公用方法,扩展短信实现时必须实现该接口
//封装短信通用接口
public interface SmsService {
//短信厂商类型 唯一标识
String getSmsType();
//发送短信
Boolean sendSms(String mobile, String content);
}
三、具体的短信实现类
这里以阿里云短信和腾讯云短信为例
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class AlibabaSmsServiceImpl implements SmsService {
@Override
public String getSmsType() {
return "alibaba";
}
@Override
public Boolean sendSms(String mobile, String content) {
log.info("执行阿里云短信业务代码,手机号:{},短信内容:{}",mobile,content);
return true;
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class TencentSmsServiceImpl implements SmsService {
@Override
public String getSmsType() {
return "tencent";
}
@Override
public Boolean sendSms(String mobile, String content) {
log.info("执行腾讯云短信业务代码,手机号:{},短信内容:{}",mobile,content);
return true;
}
}
四、接口调用
//根据厂商唯一标识获取对应的实现类,调用发送短信接口
SmsFactory.getSmsService("tencent").sendSms("11", "111");
log.info("==========================华丽的分割线==============================");
SmsFactory.getSmsService("alibaba").sendSms("22", "222");
执行结果:
如需扩展新的短信厂商能力时,只需新增实现类实现SmsService即可