前言
hello,大家好,前面讲过一篇策略模式,后来发现哪种方法有个bug,那就是实现类里面使用mapper或者dao,发现是个空的。
原因
其实原因是这种方法实则是new了一个接口,然后相继里面的bean肯定都是空的,那么怎么解决呢,今天叫一个新的处理方式。
解决
废话不多说,直接开干
1、创建枚举
public enum InternetTableEnum {
SERIOUS_PROBLEM("seriousProblem","严重问题", "com.vivo.qa.test.system.service.impl.InterSeriousProblemServiceImpl"),
LOGGING("logging","日志记录", "com.vivo.qa.test.system.service.impl.InterLoggingServiceImpl");
private String type;
private String name;
private String className;
InternetTableEnum(String className) {
this.setClassName(className);
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
InternetTableEnum(String type, String name, String className) {
this.type = type;
this.name = name;
this.className = className;
}
}
2、循环接口判断匹配type
@Autowired
private List<InterCommonService> serviceList;
public InterCommonService getInterComService(String type) {
for (InterCommonService interCommonService: serviceList) {
if (interCommonService.getTableEnum().name().equalsIgnoreCase(type)) {
return interCommonService;
}
}
return null;
}
3、接口
public interface InterCommonService {
InternetTableEnum getTableEnum();
/**
* 互联网列表查询功能
* @param paramDTO 参数
* @return list集合
*/
default List<HashMap<String, Object>> queryByPage(InternetParamDTO paramDTO) {
return new ArrayList<>();
};
}
4.1、实现类
@Service
@Transactional
public class InterSeriousProblemServiceImpl implements InterCommonService {
@Resource
private NetSeriousProblemMapper netSeriousProblemMapper;
public InternetTableEnum getTableEnum() {
return InternetTableEnum.SERIOUS_PROBLEM;
}
@Override
public List<HashMap<String, Object>> queryByPage(InternetParamDTO paramDTO) {
List<HashMap<String, Object>> list = netSeriousProblemMapper.selectAllByParam(paramDTO);
return list;
}
}
4.2、再写一个实现类
这里就不写了,直接上面4.1、复制一个即可
5、调用
List<HashMap<String, Object>> list = getInterComService(paramDTO.getType()).queryByPage(paramDTO);
后续
好了到这里,就告一段落了,这种写法思路是定义一个接口所有的枚举实现集合,然后循环遍历前端传过来的type,从而达到当前接口实现类的bean,然后在调用你想要的方法,这种就是工厂+策略模式结合。