本文共 2425 字,大约阅读时间需要 8 分钟。
在实际开发中,往往不是简单 if-else 结构,我们通常会不经意间写下如下代码:
if (money >= 1000) { if (type == UserType.SILVER_VIP.getCode()) { System.out.println("白银会员 优惠50元"); result = money - 50; } else if (type == UserType.GOLD_VIP.getCode()) { System.out.println("黄金会员 8折"); result = money * 0.8; } else if (type == UserType.PLATINUM_VIP.getCode()) { System.out.println("白金会员 优惠50元,再打7折"); result = (money - 50) * 0.7; } else { System.out.println("普通会员 不打折"); result = money; }}
后面还有很多这样的代码,让人看起来很麻烦。如果有人维护这样的代码,是不是很痛苦。
有没有更好的方法?
比如这里有个会员的需求:
根据用户VIP等级,计算出用户最终的费用
普通会员 不打折白银会员 优惠50元黄金会员 8折白金会员 优惠50元,再打7折
一般程序员实现逻辑:
private static double getResult(long money, int type) { double result = money; if (money >= 1000) { if (type == UserType.SILVER_VIP.getCode()) { System.out.println("白银会员 优惠50元"); result = money - 50; } else if (type == UserType.GOLD_VIP.getCode()) { System.out.println("黄金会员 8折"); result = money * 0.8; } else if (type == UserType.PLATINUM_VIP.getCode()) { System.out.println("白金会员 优惠50元,再打7折"); result = (money - 50) * 0.7; } else { System.out.println("普通会员 不打折"); result = money; } } return result;}
其实这里可以采用策略模式来替换
策略模式:就是把每一种if-else用一个类来实现,在if判断之后,实例化具体的类来实现具体的业务逻辑代码。
先定义一个借口
public interface Strategy { // 计费方法 double compute(long money);}
然后具体的策略实现具体的业务类
// 普通会员策略public class OrdinaryStrategy implements Strategy { @Override public double compute(long money) { System.out.println("普通会员 不打折"); return money; }}// 白银会员策略public class SilverStrategy implements Strategy { @Override public double compute(long money) { System.out.println("白银会员 优惠50元"); return money - 50; }}
然后在if-else里面实例化具体的策略类即可
private static double getResult(long money, int type) { if (money < 1000) { return money; } Strategy strategy; if (type == UserType.SILVER_VIP.getCode()) { strategy = new SilverStrategy(); } else if (type == UserType.GOLD_VIP.getCode()) { strategy = new GoldStrategy(); } else if (type == UserType.PLATINUM_VIP.getCode()) { strategy = new PlatinumStrategy(); } else { strategy = new OrdinaryStrategy(); } return strategy.compute(money);}
这里策略模式就做完了。大家体会下。
以上就是我在开发中遇到复杂的 if-else 语句“优雅处理”思路,如有不妥,欢迎大家一起交流学习
欢迎关注
转载地址:http://didsn.baihongyu.com/