欢迎光临
我们一直在努力

策略模式不是 Map 替代 if-else 就完事了——Spring 怎么用它做路由分发的

策略模式不是 Map 替代 if-else 就完事了——Spring 怎么用它做路由分发的

有个面试很经典的场景题:“怎么优化这段 if-else?”

public BigDecimal calculatePrice(Order order) {


if (order.getType() == OrderType.NORMAL) {


return order.getAmount().multiply(new BigDecimal(\”1.0\”));
} else if (order.getType() == OrderType.VIP) {


return order.getAmount().multiply(new BigDecimal(\”0.9\”));
} else if (order.getType() == OrderType.SVIP) {


return order.getAmount().multiply(new BigDecimal(\”0.8\”));
} else if (order.getType() == OrderType.WHOLESALE) {


return order.getAmount().multiply(new BigDecimal(\”0.7\”))
.subtract(new BigDecimal(\”50\”));
}
throw new IllegalArgumentException(\”unknown type\”);
}

标准答案是策略模式 + Map:

@Component
public class PriceCalculator {


private Map<OrderType

赞(0)
未经允许不得转载:171主机测评 » 策略模式不是 Map 替代 if-else 就完事了——Spring 怎么用它做路由分发的
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址