需求
定时任务模块要为多个服务提供定时任务,不同服务的定时任务执行的方式不一样,那么我们在写代码时,就需要根据不同服务的定时任务去执行对应的方法,我们想要消除多个if-else的情况,增强代码的可扩展性
原先代码
controller层
businessType是一个枚举:1 app 2 web 3interface
if (reqJson.optInt("businessType") == BusinessType.app.getValue()) {
result = quartzJobService.addApp(reqJson);
} else if (reqJson.optInt("businessType") == BusinessType.web.getValue()) {
result = quartzJobService.addWeb(reqJson);
} eles if(reqJson.optInt("businessType") == BusinessType.Interface.getValue()) {
result = quartzJobService.addInterface(reqJson);
} ....
service层
@Service
public class QuartzJobServiceImpl extends ServiceImpl<QuartzJobMapper, QuartzJob> implements IQuartzJobService {
@Override
public Integer addWeb(JSONObject reqJson) throws Exception {
}
@Override
public Integer addApp(JSONObject reqJson) throws Exception {
}
@Override
public Integer addInterface(JSONObject reqJson) throws Exception {
}
}
缺点
如果要新增一个定时任务类型,那么我们需要在原先代码上修改,在controller层增加if-else,在service层增加一个方法
解决方案
工厂模式+策略模式
工厂类
/**
* 定时任务类型工厂,项目启动将定时任务所有类型注册到map中,根据businessType得到对应的实体类
*/
public class QuartzFactory {
private static Map<String, IQuartz> quartzMap = new HashMap<>();
public static IQuartz getType(String type) {
return quartzMap.get(type);
}
public static void register(String type, IQuartz iQuartz) {
quartzMap.put(type, iQuartz);
}
}
service层
重点:
实现InitializingBean类,重写afterPropertiesSet方法,程序启动的时候,回调用afterPropertiesSet方法,put到map中,启动成功,我们就可以使用该map
public interface IQuartz {
/**
* 添加定时任务
*
* @param reqJson
* @return
*/
Integer add(JSONObject reqJson) throws Exception;
}
@Service
public class WebQuartz implements IQuartz, InitializingBean {
@Override
public Integer add(JSONObject reqJson) throws Exception {
}
@Override
public void afterPropertiesSet() throws Exception {
QuartzFactory.register("2", this);
}
}
@Service
public class AppQuartz implements IQuartz, InitializingBean {
@Override
public Integer add(JSONObject reqJson) throws Exception {
}
@Override
public void afterPropertiesSet() throws Exception {
QuartzFactory.register("1", this);
}
}
Controller层
IQuartz quartz = QuartzFactory.getType(reqJson.optString("businessType"));
quartz.add(reqJson);
优点
如果我们在新增一种定时任务,那么我们只需要创建一个新类,实现IQuartz接口即可,不需要改动已有的代码