1. 场景
当我需要调用其他其他接口,这个接口某个参数需要根据不同情况来传递不同的固定值
如:B接口调用A接口,A接口中需要传递授权码,这个授权码在不同的业务场景不同的手机系统需要传递不同的值,普通的传值方式如下:
public void notEnum(Request req) {
TestReq testReq = new TestReq();//A接口的请求
if("android".equals(req.getSysType())) {
if("a".equals(req.getBusinessType())) {
testReq.setSign("android_aaaaaaaaaaa");
} else if("b".equals(req.getBusinessType())) {
testReq.setSign("android_bbbbbbbbbbb");
} else if("c".equals(req.getBusinessType())) {
testReq.setSign("android_ccccccccccc");
}
} else if("ios".equals(req.sysType)) {
if("a".equals(req.getBusinessType())) {
testReq.setSign("ios_aaaaaaaaaaa");
} else if("b".equals(req.getBusinessType())) {
testReq.setSign("ios_bbbbbbbbbbb");
} else if("c".equals(req.getBusinessType())) {
testReq.setSign("ios_ccccccccccc");
}
}
}
17行 if else 看着贼&*¥#@难受!我就赋个值而已!而且值还是死的。
2.优化
定义enum:
public enum TestEnum {
A_ANDROID("a", "android", "android_aaaaaaaaaaa"),
A_IOS("a", "ios", "ios_aaaaaaaaaaa"),
B_ANDROID("b", "android", "android_bbbbbbbbbbb"),
B_IOS("b", "ios", "ios_bbbbbbbbbbb"),
C_ANDROID("c", "android", "android_ccccccccccc"),
C_IOS("c", "ios", "ios_ccccccccccc");
private String type;
private String source;
private String code;
TestEnum(String type, String source, String code) {
this.type = type;
this.source = source;
this.code = code;
}
public static String getCodeByTypeAndSource(String type, String source) {
TestEnum[] enums = TestEnum.values();
for(TestEnum item : enums) {
if(item.type.equals(type) && item.source.equals(source)) {
return item.code;
}
}
}
}
简化后的代码:
public void useEnum(Request req) {
TestReq testReq = new TestReq();//A接口的请求
testReq.setSign(TestEnum.getCodeByTypeAndSource(req.getBusinessType(), req.getSysType());
}
备注:如果第三个不是常量而是变量,如何解决?其实个人觉得这种情况使用map更合适。