背景
根据不同类型,获取类似的处理结果。如果使用if做判断,则会造成代码冗余且不美观。
public String getTagNum(String tagType, Integer dataClass, String tagNo) {
String[] type = {};
if("typeA".equals(tagType)){
type = new String[]{"AG-", "AT-", "AIT-"};
}
if("typeB".equals(tagType)){
type = new String[]{"BG-", "BT-", "BIT-"};
}
if("typeC".equals(tagType)){
type = new String[]{"CG-", "CT-", "CIT-"};
}
return type[dataClass] + tagNo;
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓以下为使用Lambda改造的方法↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓:
1、创建if条件的枚举类
这里创建的枚举对象,其实就是if中的判断值,枚举对象的方法里,就是希望通过这个条件获得到的东西,比如
public enum TagType {
//类型A
TYPE_A(new String[]{"AG-", "AT-", "AIT-"}),
//类型B
TYPE_B(new String[]{"BG-", "BT-", "BIT-"}),
//类型C
TYPE_C(new String[]{"CG-", "CT-", "CIT-"});
private final String[] type;
TagType (String[] type) {
this.type = type;
}
public String[] getValue() {
return type;
}
}
2、创建公共处理方法
这个方法里,入参包含两方面:要用到的公共处理参数以及核心接口,方法体主要包含通过核心接口Function(java.util.function.Function)获取的枚举类中对应的方法,以及公共处理逻辑,,比如:
public String getTagNum(TagType tagType, Integer dataClass, String tagNo, Function<TagType, String[]> fc) {
for (TagType value : TagType.values()) {
if (value == tagType) {
String[] strArry = fc.apply(value);
return strArry[dataClass] + tagNo;
}
}
return null;
}
3、调用
getKsTagNum(TagType.TYPE_A, 1, "111", (x) -> TagType.TYPE_A.getValue());
只为记录学习,勿喷,如果诸位有更好的改进方法,欢迎指出,不胜感激。