学无先后,达者为师

网站首页 编程语言 正文

Map+函数式接口(替换if-else)

作者:小徐敲java 更新时间: 2024-04-03 编程语言

用上了Java8的新特性lambda表达式,判断条件放在key中,对应的业务逻辑放在value中

@Service  
public class QueryGrantTypeService {  
   
    @Autowired  
    private GrantTypeSerive grantTypeSerive;  
    private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();  
  
    /**  
     *  初始化业务分派逻辑,代替了if-else部分  
     *  key: 优惠券类型  
     *  value: lambda表达式,最终会获得该优惠券的发放方式  
     */  
    @PostConstruct  
    public void dispatcherInit(){  
        grantTypeMap.put("红包",resourceId->grantTypeSerive.redPaper(resourceId));  
        grantTypeMap.put("购物券",resourceId->grantTypeSerive.shopping(resourceId));  
        grantTypeMap.put("qq会员",resourceId->grantTypeSerive.QQVip(resourceId));  
    }  
   
    public String getResult(String resourceType){  
        //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType  
        Function<String,String> result=getGrantTypeMap.get(resourceType);  
        if(result!=null){  
         //传入resourceId 执行这段表达式获得String型的grantType  
            return result.apply(resourceId);  
        }  
        return "查询不到该优惠券的发放方式";  
    }  
}  
  
@Service  
public class GrantTypeSerive {  
  
    public String redPaper(String resourceId){  
     
        return "红包的发放方式";  
    }  
    public String shopping(String resourceId){  
       
        return "购物券的发放方式";  
    }  
    public String qqVip(String resourceId){  
        
        return "qq会员的发放方式";  
    }  
}  
@RestController  
public class GrantTypeController {  
  
    @Autowired  
    private QueryGrantTypeService queryGrantTypeService;  
  
    @PostMapping("/grantType")  
    public String test(String resourceName){  
        return queryGrantTypeService.getResult(resourceName);  
    }  
}  

原文链接:https://blog.csdn.net/qq_19891197/article/details/136299162

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新