本文最后更新于130 天前,其中的信息可能已经过时,如有错误请发送邮件到[email protected]
这里描述的问题和一中描述的问题差不多,只是这里提供另一种写法。
/**
* 这里就是通过策略模式去更新状态的一个业务
*/
@Component
public abstract class StatusUpdateStrategy {
@Autowired
protected ScreenRecordAlgoMapper screenRecordAlgoMapper;
@Autowired
protected ScreeningOptRecordMapper screeningOptRecordMapper;
/**
* 封装更新对象
*
* @param screenRecordAlgoDO 筛查对象
* @param status 要更新的状态码
*/
public abstract void buildDO(ScreenRecordAlgoDO screenRecordAlgoDO, Integer status);
// 更新状态
public void update(ScreenRecordAlgoDO screenRecordAlgoDO, String message) {
// 更新 ScreenRecordAlgoDO
screenRecordAlgoMapper.updateById(screenRecordAlgoDO);
// 更新日志
ScreeningOptRecordDO screeningOptRecordDO = new ScreeningOptRecordDO();
screeningOptRecordDO.setScreenRecordAlgoDOId(screenRecordAlgoDO.getId());
// .......
screeningOptRecordMapper.insert(screeningOptRecordDO);
}
}
@Component
public class StatusUpdateStrategyFactory {
@Autowired
private DayFollowupStrategy dayFollowupStrategy;
@Autowired
private ReInpatientStrategy reInpatientStrategy;
@Autowired
private ReScreeningStrategy reScreeningStrategy;
// 可以拓展更多的子类
public StatusUpdateStrategy getStrategy(Integer type) {
switch (type) {
case 1:
return dayFollowupStrategy;
case 2:
return reInpatientStrategy;
case 3:
return reScreeningStrategy;
// ........
default:
throw new IllegalArgumentException("Invalid type: " + type);
}
}
}
@Component
public class ReScreeningStrategy extends StatusUpdateStrategy {
private static final Map<Integer, String> statusMap = Map.of(
0, "取消",
1, "标记"
);
@Override
public void updateStatus(ScreenRecordAlgoDO screenRecordAlgoDO, Integer status) {
screenRecordAlgoDO.setReScreeningFlag(status);
update(screenRecordAlgoDO, statusMap.get(status));
}
}
// 其余子类都是这个写法
// 或者其他注入的方式
@Autowired
private StatusUpdateStrategyFactory statusUpdateStrategyFactory;
// 在service中的写法
@Override
@Transactional(rollbackFor = Exception.class)
public void updateDynamicStatus(Long id, Integer status, Integer type) {
ScreenRecordAlgoDO screenRecordAlgoDO = screenRecordAlgoMapper.selectById(id);
// 获取对应的策略
StatusUpdateStrategy strategy = statusUpdateStrategyFactory.getStrategy(type);
// 执行策略
strategy.updateStatus(screenRecordAlgoDO, status);
}