利用Java 8的Function接口来消灭if...else...
可以通过function函数和map,来消灭if...else...,通过此方式,达到的效果是:逻辑清楚,代码简洁,很大程度上解决了策略模式中弊端。
1.定义service类
public interface GrantTypeService {public String beijing(String resourceId);public String shanghai(String resourceId);public String qingdao(String resourceId);
}
2.定义ServiceImpl
public class GrantTypeServiceImpl implements GrantTypeService{public String beijing(String resourceId){return "北京";}public String shanghai(String resourceId){return "上海";}public String qingdao(String resourceId){return "青岛";}}
3.通过map和function函数获取结果,此方式消灭了if...else...
public String getResult(String resourceType) {Map> grantTypeMap = new HashMap<>();grantTypeMap.put("北京", resourceId -> grantTypeService.beijing(resourceId));grantTypeMap.put("上海", resourceId-> grantTypeService.shanghai(resourceId));grantTypeMap.put("青岛", resourceId -> grantTypeService.qingdao(resourceId));Function result = grantTypeMap.get(resourceType);System.out.println("result" + result.toString());if (result != null) {System.out.println(result.apply(resourceType));return result.apply(resourceType);}return "找不到地方";}

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
