繁体   English   中英

如何使用Temple方法,泛型方法或其他方法优化代码?现在我必须编写三遍类似的代码

[英]How to optimize my code using temple method or generic method or other method?Now I have to write the similar code three times

现在,我想将消息发送给可能是学生,老师或校长的人,他们所有人都有电话,姓名和availdSendMsgCount。在发送消息之前,这意味着将数据插入数据库,我必须判断他们是否可以无论是否发送,所以我写这样的代码:

if(sendType=SendType.student){
 List<Student> students=tStudentServiceImpl.queryByParam(conditionMap);
         sendPhoneCout=students.size(); 
         checkSendNumber(availdSendMsgCount,sendPhoneCout); 
Log log=logMsgSend(content,sendPhoneCout,sendType); 
         for (Student vo : students)      
 sendMsgItem(content,vo.getPhone(),vo.getName(),vo.getId(),log.getId()); 
}
 else if(sendType=SendType.teacher){
 List<Teacher> teachers=tTeacherServiceImpl.queryByParam(conditionMap);
         sendPhoneCout=teachers.size(); 
         checkSendNumber(availdSendMsgCount,sendPhoneCout); 
     Log log=logMsgSend(content,sendPhoneCout,sendType); 
         for (Teacher vo : teachers)      
   sendMsgItem(content,vo.getPhone(),vo.getName(),vo.getId(),log.getId()); 
}
else{
  List<Schoolmaster>  schoolmasters=tSchoolmasterServiceImpl.queryByParam(conditionMap);
         sendPhoneCout=schoolmasters.size(); 
         checkSendNumber(availdSendMsgCount,sendPhoneCout); 
     Log log=logMsgSend(content,sendPhoneCout,sendType); 
         for (Schoolmaster vo : schoolmasters)      
   sendMsgItem(content,vo.getMasterPhone(),vo.getMasterName(),vo.getId(),log.getId()); 
 }

我认为这段代码不好,但是如何优化呢?

当校长,老师和学生实现相同的接口或超类时,则可以编写一个使用List作为参数的方法,该方法可以完成所有工作,并且在三种情况下都将被调用。

另一方面,为什么会有三个不同的班级? 他们似乎有完全相同的方法。 一个类型参数决定它是哪种类型还不够吗?

我建议您创建一个接口并在您的dao类中实现它,这样每个接口的行为都会有所不同。

public interface NameMe {
      void sendMsgItem(content, Integer logId); // it's not clear the type of content
}

有方法

// replace T with type of 'conditionMap' object, it's not clear from your code
public static void getAndSendMessageItems(Function<T, List<NameMe>> serviceFunc,
        T conditionMap, Integer availdSendMsgCount, SendType sendType) { 
    List<NameMe> values = serviceFunc.apply(conditionMap);
    Integer sendPhoneCout = values.size(); 
    checkSendNumber(availdSendMsgCount, sendPhoneCout); 
    Log log = logMsgSend(content, sendPhoneCout, sendType); 
    for (NameMe i : values) {     
         i.sendMsgItem(content, log.getId());            
    }
}

并在您的if / else中调用它

Function<T, List<NameMe>> serviceFunc = null; 
if (SendType.student.equals(sendType)) {
    serviceFunc = tStudentServiceImpl::queryByParam;
} else if (SendType.teacher.equals(sendType)) {
    serviceFunc = tTeacherServiceImpl::queryByParam;
} else {
    serviceFunc = tSchoolmasterServiceImpl::queryByParam;
}
getAndSendMessageItems(serviceFunc, conditionMap, availdSendMsgCount, sendType);

但是,如果您的服务实现相同的接口,则甚至不需要使用Function<T, List<NameMe>> ,您只需通过接口对象传递服务即可。

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM