这是一个简单的if-else
public void operationByWorkItemType(String studentType){
if("bks".equals(workItemType)){
doBksOperation();
}else if("sss".equals(workItemType)){
doSssOperation();
}else if("bss".equals(workItemType)){
doBssOperation();
}
、、、、、、
}
定义一个接口
public interface StudentTypeOperation {
/**
* 根据studentType不同,对应操作不同
*/
void operate();
}
有几个判断定义几个类
@Component
@AllArgsConstructor
public class BksStrategy implements StudentTypeOperation {
@Override
public void operate() {
doBksOperation();
}
}
@Component
@AllArgsConstructor
public class SssStrategy implements StudentTypeOperation {
@Override
public void operate() {
doSssOperation();
}
}
@Component
@AllArgsConstructor
public class BssStrategy implements StudentTypeOperation {
@Override
public void operate() {
doBssOperation();
}
}
将这些spring管理的实例注入静态map
SpringUtil是hutool工具类的
public class StudentTypeFactory {
private static final Map<String,StudentTypeOperation> STUDENT_ITEM_TYPE_MAP =new HashMap<>();
static {
STUDENT_ITEM_TYPE_MAP.put("sss", SpringUtil.getBean(PasswordTokenGranter.class));
STUDENT_ITEM_TYPE_MAP.put("sssss", SpringUtil.getBean(CaptchaTokenGranter.class));
STUDENT_ITEM_TYPE_MAP.put("three", SpringUtil.getBean(RefreshTokenGranter.class));
STUDENT_ITEM_TYPE_MAP.put("fore", SpringUtil.getBean(SocialTokenGranter.class));
}
public static void operate(String studentType){
STUDENT_ITEM_TYPE_MAP.get(studentType).operate();
}
}
调用
public void operationByStudentType(String studentType){
StudentTypeFactory.operate(studentType);
}