使用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){}

}


### 如何使用函数指针替代if-else实现代码逻辑 #### C++ 实现示例 在C++中,可以利用函数指针来简化条件判断逻辑。通过创建一个映射表(如`std::map`或数组),将特定的操作绑定到相应的键上,从而避免冗长的if-else语句。 ```cpp #include <iostream> #include <functional> #include <unordered_map> // 定义操作接口 using OperationFunc = std::function<void()>; void addOperation() { std::cout << "Add operation called." << std::endl; } void subtractOperation() { std::cout << "Subtract operation called." << std::endl; } int main() { // 创建操作映射表 std::unordered_map<std::string, OperationFunc> operations{ {"add", addOperation}, {"subtract", subtractOperation} }; // 用户输入命令 std::string command; std::cin >> command; // 执行对应操作 auto it = operations.find(command); if (it != operations.end()) { it->second(); // 调用对应的函数 } else { std::cerr << "Unknown command!" << std::endl; } return 0; } ``` 此方法不仅提高了代码可读性和维护性,还使得扩展新功能变得更为容易[^1]。 #### C# 实现示例 同样,在C#里也可以采用类似的策略模式来代替传统的if-else分支: ```csharp using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Dictionary<string, Action> actions = new Dictionary<string, Action>() { { "add", Add }, { "subtract", Subtract } }; Console.WriteLine("Enter action:"); string inputAction = Console.ReadLine(); if(actions.ContainsKey(inputAction)) { actions[inputAction].Invoke(); } else { Console.WriteLine($"Invalid action '{inputAction}'"); } } private static void Add() => Console.WriteLine("Performing addition..."); private static void Subtract() => Console.WriteLine("Performing subtraction..."); } ``` 这种方式增强了程序灵活性并减少了重复代码量[^2]. #### Java 实现示例 Java 中可以通过 `Map<String, Runnable>` 来存储不同类型的处理逻辑,并根据给定的关键字执行相应的行为: ```java import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class FunctionPointerExample { public static void main(String[] args) { Map<String, Runnable> commands = new HashMap<>(); commands.put("add", () -> performAddition()); commands.put("sub", () -> performSubtraction()); Scanner scanner = new Scanner(System.in); System.out.print("Choose an option(add/sub): "); String choice = scanner.nextLine().trim().toLowerCase(); commands.getOrDefault(choice, () -> System.out.println("Invalid Choice")).run(); } private static void performAddition(){ System.out.println("Executing Addition Logic."); } private static void performSubtraction(){ System.out.println("Executing Subtraction Logic."); } } ``` 这种方法使代码更加简洁明了,同时也便于后期的功能扩充和修改[^3].
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值