private String getPositioningType(String customerType,String positioningType) {
String type = "";
if ("1".equals(customerType)) {
switch (positioningType) {
case "1":
type = "小米";
break;
case "2":
type = "小红";
break;
case "3":
type = "小李";
break;
}
} else if ("2".equals(customerType)) {
switch (positioningType) {
case "1":
type = "李老师";
break;
case "2":
type = "王老师";
break;
case "3":
type = "张老师";
break;
}
}
return type;
}
现在有这样一段代码,根据多个不同的类型匹配返回相应的值,如果类型越多,那代码中的if判断也会很长,显得不那么友好,所以对上面代码进行相应的优化;
使用Map和枚举类型
public enum CustomerType {
INDIVIDUAL("1") {
@Override
public String getTypeByCode(String code) {
return INDIVIDUAL_TYPE_MAP.getOrDefault(code, "");
}
},
ORGANIZATION("2") {
@Override
public String getTypeByCode(String code) {
return ORGANIZATION_TYPE_MAP.getOrDefault(code, "");
}
};
//每种客户类型,使用Map来存储其可能的定位类型
private static final Map<String, String> INDIVIDUAL_TYPE_MAP = new HashMap<String, String>() {{
put("1", "小米");
put("2", "小红");
put("3", "小李");
}};
private static final Map<String, String> ORGANIZATION_TYPE_MAP = new HashMap<String, String>() {{
put("1", "李老师");
put("2", "王老师");
put("3", "张老师");
}};
private final String code;
CustomerType(String code) {
this.code = code;
}
public static CustomerType getByCode(String code) {
for (CustomerType customerType : values()) {
if (customerType.code.equals(code)) {
return customerType;
}
}
return null;
}
public abstract String getTypeByCode(String code);
}
出入参数调用方法:
private static String getPositioningType(String customerType, String positioningType) {
CustomerType type = CustomerType.getByCode(customerType);
if (type != null) {
return type.getTypeByCode(positioningType);
}
return "";
}
使用枚举类型来表示不同的客户类型,并为每个类型提供一个抽象方法getTypeByCode()。该方法在每个枚举常量中实现,以返回指定代码的定位类型。通过静态方法getByCode(),我们可以根据传入的代码获取对应的客户类型。如果找不到匹配的客户类型,则返回null。
对于每种客户类型,我们都使用Map来存储其可能的定位类型。在getPositioningType()方法中,我们首先使用getByCode()方法获取相应的客户类型。如果找到了匹配的客户类型,则调用其getTypeByCode()方法获取对应的定位类型。如果找不到匹配的客户类型,则返回一个空字符串。