定时任务---工厂模式+策略模式消除多if,增强代码扩展性

需求

定时任务模块要为多个服务提供定时任务,不同服务的定时任务执行的方式不一样,那么我们在写代码时,就需要根据不同服务的定时任务去执行对应的方法,我们想要消除多个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接口即可,不需要改动已有的代码

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值