1. 为什么 10000 个 if-else 是个问题?
if (condition1) {
// do something
} else if (condition2) {
// do something else
} else if (condition3) {
// ...
} else if (condition10000) {
// ...
}
可维护性低:你敢改,我就敢给你鼓掌。逻辑一改,bug 随时冒出来,还不如从头重写。 性能问题:如果条件判断顺序不好,可能需要逐个匹配所有条件,简直就是 CPU 的噩梦。 阅读难度爆表:团队协作时,敢看这种代码的人,一定是勇士。
2. 优化套路大放送
2.1 策略模式:化繁为简
// 定义策略接口
public interface PaymentStrategy {
void pay(int amount);
}
// 实现不同策略
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
public class PayPalPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// 使用策略模式
public class PaymentProcessor {
private Map<String, PaymentStrategy> strategyMap;
public PaymentProcessor() {
strategyMap = new HashMap<>();
strategyMap.put("CREDIT_CARD", new CreditCardPayment());
strategyMap.put("PAYPAL", new PayPalPayment());
}
public void processPayment(String type, int amount) {
PaymentStrategy strategy = strategyMap.get(type);
if (strategy != null) {
strategy.pay(amount);
} else {
throw new IllegalArgumentException("Unsupported payment type: " + type);
}
}
}
2.2 Map 映射:简化条件查找
Map<String, Runnable> actions = new HashMap<>();
actions.put("ADMIN", () -> System.out.println("Welcome Admin!"));
actions.put("USER", () -> System.out.println("Welcome User!"));
actions.put("GUEST", () -> System.out.println("Welcome Guest!"));
// 执行逻辑
String role = "USER";
actions.getOrDefault(role, () -> System.out.println("Role not recognized.")).run();
2.3 使用枚举
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public String getTaskForDay(Day day) {
switch (day) {
case MONDAY:
return "Start fresh!";
case FRIDAY:
return "Wrap up!";
case SUNDAY:
return "Relax!";
default:
return "Keep going!";
}
}
2.4 规则引擎:把逻辑交给专业工具
// 定义规则文件 (drl)
rule "Discount for VIP"
when
user.level == "VIP"
then
user.discount = 20;
end
2.5 快速返回:别让代码绕圈子
public String getDiscount(int age) {
if (age < 18) return "Youth Discount";
if (age > 60) return "Senior Discount";
return "No Discount";
}
2.6 函数式编程:链式调用
Stream
:List<String> roles = Arrays.asList("ADMIN", "USER", "GUEST");
roles.stream()
.filter(role -> role.equals("ADMIN"))
.forEach(role -> System.out.println("Welcome " + role + "!"));
3. 怎么选?
如果条件固定、数量少:用枚举或者快速返回。 如果条件复杂且容易扩展:策略模式或规则引擎更合适。 如果需要简单直接:Map 映射和三目运算符不错。
-END-
以上,就是今天的分享了,看完文章记得右下角给何老师点赞,也欢迎在评论区写下你的留言。