在做业务开发的时候,经常会用到判断,然后调用不同的方法,或者说调用同一个方法传递不同的参数。比如:
public class IFELSE {
public void doBusiness(String type){
if ("1".equals(type)) {
this.callRemoteProduce("method1");
}else if ("2".equals(type)) {
this.callRemoteProduce("method2");
}else if ("3".equals(type)) {
this.callRemoteProduce("method3");
}else if ("4".equals(type)) {
this.callRemoteProduce("method4");
}else if ("5".equals(type)) {
this.callRemoteProduce("method5");
}else if ("6".equals(type)) {
this.callRemoteProduce("method6");
}else if ("7".equals(type)) {
this.callRemoteProduce("method7");
}else if ("8".equals(type)) {
this.callRemoteProduce("method8");
}else if ("9".equals(type)) {
this.callRemoteProduce("method9");
}else if ("10".equals(type)) {
this.callRemoteProduce("method10");
}
}
private void callRemoteProduce(String method){
}
}
当分支条件太多的时候,代码看起来将会相当臃肿!这个时候,可以考虑使用map来代替分支判断。比如:
public class MapReplace {
public void doBusiness(String type){
Map<String, String> map = new HashMap<String, String>();
map.put("1", "method1");
map.put("2", "method2");
map.put("3", "method3");
map.put("4", "method4");
map.put("5", "method5");
map.put("6", "method6");
map.put("7", "method7");
map.put("8", "method8");
map.put("9", "method9");
map.put("10", "method10");
this.callRemoteProduce(map.get(type));
}
private void callRemoteProduce(String method){
}
}
但是上面的代码,每次调用方法时都会创建一个map实例对象,方法结束后又销毁map,作为常用代码可以考虑将map作为类的静态成员变量使用。代码如下:
public class MapReplace {
private static Map<String, String> map = new HashMap<String, String>(){
private static final long serialVersionUID = 1L;
{
put("1", "method1");
put("2", "method2");
put("3", "method3");
put("4", "method4");
put("5", "method5");
put("6", "method6");
put("7", "method7");
put("8", "method8");
put("9", "method9");
put("10", "method10");
}
};
public void doBusiness(String type){
this.callRemoteProduce(map.get(type));
}
private void callRemoteProduce(String method){}
}