可以通过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 "找不到地方";
}



