使用Map代替else if过多的情况

在做业务开发的时候,经常会用到判断,然后调用不同的方法,或者说调用同一个方法传递不同的参数。比如:
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){}

}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值