项目背景
最近公司需要引入一款新的人脸设备,并且想要整合一下之前的设备,想要做到一个项目里面能使用两个不同平台的设备,这两个平台之前都做过对接,但是由于写的人不同,所以逻辑上有一点点不一样,但是其实也可以按照同样的逻辑去写。
重构第一步:抽取共性与差异
注意,重构一定要在你熟悉业务与架构的情况下进行重构,如果不熟悉,并且没有必要的情况下,不建议对代码做任何修改,经过上线校验的代码,写的再差也比没经过验证的代码强。
以我这次重构的一个步骤为例,人员信息同步(增加、修改),其实他就可以抽象成以下这么一个流程
获取在线的设备 -> 检查图片质量是否合格 -> 开启线程异步同步 -> 检查设备是否存在该人员 ?修改 : 删除
重构第二步:根据第一步的流程确定架构
这里先放一下原代码,这段代码在只有一种设备的情况下是没有问题的,但是现在我这里一个程序需要兼容不同的设备,并且设备的处理逻辑大体上是相同的,只不过与设备交互的地方有点不一样
private void doSyncPerson(PersonalInfo personalInfo, OperateType operateType, UserSyncReq userInfo, String address) {
Integer deviceId;
try {
deviceId = deviceService.getDeviceId(address);
} catch (Exception e) {
throw new ServiceException("获取设备id失败,address: " + address);
}
if (isExistsPerson(address, deviceId, String.valueOf(userInfo.getUser_id()))) {
operateType = OperateType.EditPerson;
personalInfo.setOperator(operateType.name());
}
personalInfo.getInfo().setDeviceId(deviceId);
HaiqingResp response = haiqingDeviceClient.post(address, operateType, personalInfo,HaiqingResp.class);
if(response.isError()){
throw new ServiceException("同步人员信息失败");
}
}
private PersonalInfo searchPerson(String address, int deviceId, String searchId) {
Map<String, Object> json = new HashMap<>();
json.put("operator", OperateType.SearchPerson.name());
Map<String, Object> info = new HashMap();
info.put("DeviceID", deviceId);
info.put("SearchType", 0);
info.put("SearchID", searchId);
info.put("Picture", 0);
json.put("info", info);
return haiqingDeviceClient.post(address, OperateType.SearchPerson, json,PersonalInfo.class);
}
private boolean isExistsPerson(String address, int deviceId, String searchId) {
PersonalInfo personalInfo = this.searchPerson(address, deviceId, searchId);
if (personalInfo == null) {
return false;
}
if (personalInfo.getInfo() == null) {
return false;
}
return personalInfo.getInfo().getCustomizeId() != null;
}
开始重构
@Override
public AcmsRespDTO userSync(UserSyncReq userSyncReq) {
List<String> device_address_list = userSyncReq.getDevice_address_list();
userSyncReq.setDevice_address_list(filterOnlineDevices(device_address_list));
// checkImage是个接口方法 由子类实现
boolean isPass = checkImage(userSyncReq.getPhoto(), userSyncReq.getDevice_address_list());
if(!isPass){
return AcmsRespDTO.error("图片校验失败");
}
for (String address : userSyncReq.getDevice_address_list()) {
ScheduleConfig scheduleConfig = new ScheduleConfig();
scheduleConfig.setKey(IdUtil.fastSimpleUUID());
scheduleConfig.setStartTime(new Date());
scheduleConfig.setDelay(defaultDelay);
// 用户同步的抽象类
AbstractUserSyncThread userSyncThread = getUserSyncThread();
userSyncThread.setScheduleConfig(scheduleConfig);
userSyncThread.setUserSyncReq(userSyncReq);
userSyncThread.setAddress(address);
scheduleConfig.setRunnable(userSyncThread);
scheduledTaskService.addPollingTask(scheduleConfig);
}
return AcmsRespDTO.success();
}
public abstract class AbstractUserSyncThread extends AbstractScheduleTimesRunnable {
protected UserSyncReq userSyncReq;
protected String address;
@Override
protected void timesRun() {
if(checkUserExist()){
log.info("用户存在,修改");
updateUser();
}else{
log.info("用户不存在,新增");
addUser();
}
}
/**
* 检查用户是否存在 子类实现
* @return
*/
protected abstract boolean checkUserExist();
//子类实现新增方法
protected abstract void addUser();
//子类实现修改方法
protected abstract void updateUser();
public UserSyncReq getUserSyncReq() {
return userSyncReq;
}
public void setUserSyncReq(UserSyncReq userSyncReq) {
this.userSyncReq = userSyncReq;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
第三步:由子类确认具体实现
这里以其中一个设备为例
@Service("HaiQing")
@Slf4j
public class HaiQingAcmsInterface extends AbstractAcmsInterface {
@Autowired
private HaiqingDeviceClient haiqingDeviceClient;
@Override
public AcmsRespDTO usePicCheck(String photo) {
return null;
}
@Override
public boolean checkImagePass(String photo, String address) {
DetectFaceFromPicReq request = new DetectFaceFromPicReq();
request.setOperator(OperateType.DetectFaceFromPic);
DetectFaceFromPicReq.Info info = new DetectFaceFromPicReq.Info();
info.setPicinfo(photo);
request.setInfo(info);
try {
DetectFaceFromPicResp detectFaceFromPicResp = haiqingDeviceClient
.post(address, OperateType.DetectFaceFromPic, request, DetectFaceFromPicResp.class);
int detectFace = Optional.ofNullable(detectFaceFromPicResp)
.map(DetectFaceFromPicResp::getInfo)
.map(DetectFaceFromPicResp.Info::getDetectFace)
.orElse(0);
return detectFace == 1;
} catch (Exception ignored) {
log.error("校验图片异常",ignored);
}
return false;
}
@Override
public AbstractUserSyncThread getUserSyncThread() {
return new HaiQingUserSyncThread();
}
@Override
public AbstractUserDelThread getUserDelThread() {
return new HaiQingUserDelThread();
}
@Override
public AbstractDeviceSyncThread getDeviceSyncThread() {
return new HaiQingDeviceSyncThread();
}
}
public class HaiQingUserSyncThread extends AbstractUserSyncThread {
private static HaiqingDeviceClient haiqingDeviceClient = SpringUtils.getBeanByClass(HaiqingDeviceClient.class);
private static HaiQingDeviceService haiQingDeviceService = SpringUtils.getBeanByClass(HaiQingDeviceService.class);
@Override
protected boolean checkUserExist() {
return haiQingDeviceService.checkUserExist(address,userSyncReq.getUser_id());
}
@Override
protected void addUser() {
PersonalInfo personalInfo = getPersonalInfo();
personalInfo.setOperator(OperateType.AddPerson.name());
HaiqingResp response = haiqingDeviceClient.post(address, OperateType.AddPerson, personalInfo,HaiqingResp.class);
if(response.isOk()){
stop();
}
}
@Override
protected void updateUser() {
PersonalInfo personalInfo = getPersonalInfo();
personalInfo.setOperator(OperateType.EditPerson.name());
HaiqingResp response = haiqingDeviceClient.post(address, OperateType.EditPerson, personalInfo,HaiqingResp.class);
if(response.isOk()){
stop();
}
}
private PersonalInfo getPersonalInfo(){
PersonalInfo personalInfo = new PersonalInfo();
personalInfo.setPicInfo(userSyncReq.getPhoto());
Personal personal = new Personal();
personal.setIdType(0);
personal.setCustomizeId(Long.parseLong(userSyncReq.getUser_id()));
personal.setTelnum(userSyncReq.getPhone());
personal.setName(userSyncReq.getUser_name());
personalInfo.setInfo(personal);
Integer deviceId = haiQingDeviceService.getDeviceId(address);
personal.setDeviceId(deviceId);
return personalInfo;
}
}
总结
公司内部的代码也就只能放部分片段了,重构以后代码相对来说更加清晰了一些,
说说重构的好处和坏处,按照这种架构的话呢,它固定了程序的流程,让程序以一定的流程去执行,但是也减少的一定的自由性,如果有其他设备要接入的话,按照这套模式就非常简单(按照这个架构重构另一个设备的代码就只花了一个小时,在对应实现的地方把原来的代码贴上去就行),但是如果你要改架构,就会变得非常复杂,还有,这种架构也用到了模板设计模式、工厂设计模式、对于新人来说可能会难以理解。