Map+functional interface replaces multiple if-else logic

Map+functional interface is the new feature of Java8 lambda expression

  • The judgment condition is placed in the key

  • The corresponding business logic is placed in value.
    The advantage of writing it this way is that it is very intuitive and you can directly see the business logic corresponding to the judgment condition.
     

In business scenarios, when you are working on large-scale projects, it is often because a method performs different processing according to different roles.

When the organizational structure of the user is very complex, you may use multiple if elses to judge and then execute different logic. After writing, you will find that one method can reach one or two hundred lines, and it will be a headache when you modify it.

@Service
public class QueryRoleService {

    @Autowired
    private RoleSerive roleSerive;
    private Map<String, Function<String,String>> roleMap=new HashMap<>();

    /**
     *  初始化业务分派逻辑,代替了if-else部分
     *  key:
     *  value: lambda表达式
     */
    @PostConstruct
    public void dispatcherInit(){
        roleMap.put("管理员",id->roleSerive.adminPression(id));
        roleMap.put("部门领导",id->roleSerive.departPresion(id));
        roleMap.put("普通员工",id->roleSerive.employeePression(id));
    }

    public String getResult(String orgCodeName,String orgCode){
        Function<String,String> result= roleMap.get(orgCodeName);
        if(result!=null){
            return result.apply(orgCode);
        }
        return "";
    }
}
@Service
public class RoleSerive {

    public String adminPression(String id){
        return "管理员权限业务逻辑";
    }
    public String departPresion(String id){
        return "部门领导权限业务逻辑";
    }
    public String employeePression(String id){
        return "员工权限业务逻辑";
    }
}

 @PostMapping(value = "/role")
	 public Result<?> role(String orgCodeName,String orgCode) {
		 queryRoleService.getResult(orgCodeName,orgCode);
		 return Result.OK("添加成功!");
	 }

Guess you like

Origin blog.csdn.net/weixin_41018853/article/details/131893057