日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新