[解鎖新姿式] 回想起被 `if-else` 支配的恐懼,咱們要打倒 if - else

前言

[解鎖新姿式] 兄dei,你代碼須要優化了
在以前文章說到,簡單 if-else,能夠使用 衛語句 進行優化。可是在實際開發中,每每不是簡單 if-else 結構,咱們一般會不經意間寫下以下代碼:java

-------------------- 理想中的 if-else  --------------------
public void today() {
    if (isWeekend()) {
        System.out.println("玩遊戲");
    } else {
        System.out.println("上班!");
    }
}


-------------------- 現實中的 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;
    }
}


//省略 n 個 if-else ......

複製代碼

絕不誇張的說,咱們都寫過相似的代碼,回想起被 if-else 支配的恐懼,咱們經常無所下手,甚至不了了之。算法

下面分享一下我在開發中遇到複雜的 if-else 語句「優雅處理」思路。若有不妥,歡迎你們一塊兒交流學習。ide

需求

假設有這麼一個需求:post

一個電商系統,當用戶消費滿1000 金額,能夠根據用戶VIP等級,享受打折優惠。學習

根據用戶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 會進行複雜的邏輯計費。 從功能上來講,基本完成,可是對於我這種有代碼潔癖的人來講,代碼質量上不忍直視。咱們開始着手 優化一下咱們的初版代碼吧。google

思考

看到如上代碼,聰明的朋友首先想到的是,這不是典型的策略模式嗎?編碼

你可真是個機靈鬼,咱們先嚐試用策略模式來優化一下代碼吧。spa

策略模式

什麼是策略模式?

可能有的朋友還不清楚,什麼是策略模式。策略模式是定義一系列的算法,把它們一個個封裝起來, 而且使它們可相互替換code

好比上述需求,有返利、有打折、有折上折等等。這些算法自己就是一種策略。而且這些算法能夠相互替換的,好比今天我想讓 白銀會員優惠50,明天能夠替換爲 白銀會員打9折

說了那麼多,不如編碼來得實在。

編碼

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;
    }
}

// 黃金會員策略
public class GoldStrategy implements Strategy{

    @Override
    public double compute(long money) {
        System.out.println("黃金會員 8折");
        return money * 0.8;
    }
}

// 白金會員策略
public class PlatinumStrategy implements Strategy {
    @Override
    public double compute(long money) {
        System.out.println("白金會員 優惠50元,再打7折");
        return (money - 50) * 0.7;
    }
}
複製代碼

咱們定義來一個 Strategy 接口,而且定義 四個子類,實現接口。在對應的 compute方法 實現自身策略的計費邏輯。

private static double getResult(long money, int type) {

    double result = money;

    if (money >= 1000) {
        if (type == UserType.SILVER_VIP.getCode()) {

            result = new SilverStrategy().compute(money);
        } else if (type == UserType.GOLD_VIP.getCode()) {

            result = new GoldStrategy().compute(money);
        } else if (type == UserType.PLATINUM_VIP.getCode()) {

            result = new PlatinumStrategy().compute(money);
        } else {
            result = new OrdinaryStrategy().compute(money);
        }
    }

    return result;
}
複製代碼

而後對應 getResult 方法,根據 type 替換爲對應的 用戶VIP 策略。 這裏代碼上出現了重複的調用 compute ,咱們能夠嘗試進一步優化。

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);
}
複製代碼

還記得我在第一篇中說到的衛語句嗎? 咱們在這裏把 money < 1000 的狀況提早 return。更關注於滿1000邏輯 ,也能夠減小沒必要要的縮進。

深思

我曾一度 覺得 策略模式不過如此。覺得代碼優化到這已經能夠了。

可是還有一個恐怖的事情,if-else 依然存在 :)

我嘗試翻閱了許多書籍,查看如何消除 策略模式中的 if-else

書中大部分的方法是,使用簡單工廠 + 策略模式。把 if - else 切換爲 switch 建立一個工廠方法而已。

可是這遠遠沒有達到我想要的效果,打倒 if - else

直到某一天夜裏,我大佬在羣裏分享一個 Java8 小技巧時,今後大開新世界。

工廠 + 策略

public interface Strategy {

    double compute(long money);

    // 返回 type
    int getType();
}


public class OrdinaryStrategy implements Strategy {

    @Override
    public double compute(long money) {
        System.out.println("普通會員 不打折");
        return money;
    }

    // 添加 type 返回
    @Override
    public int getType() {
        return UserType.SILVER_VIP.getCode();
    }
}

public class SilverStrategy implements Strategy {

    @Override
    public double compute(long money) {

        System.out.println("白銀會員 優惠50元");
        return money - 50;
    }

    // type 返回
    @Override
    public int getType() {
        return UserType.SILVER_VIP.getCode();
    }
}

....省略剩下 Strategy
複製代碼

咱們先在 Strategy 新增一個 getType 方法,用來標示 該策略的 type 值。代碼相對簡單,這裏就不過多介紹了

public class StrategyFactory {

    private Map<Integer, Strategy> map;

    public StrategyFactory() {

        List<Strategy> strategies = new ArrayList<>();

        strategies.add(new OrdinaryStrategy());
        strategies.add(new SilverStrategy());
        strategies.add(new GoldStrategy());
        strategies.add(new PlatinumStrategy());
        strategies.add(new PlatinumStrategy());

        // 看這裏 看這裏 看這裏!
        map = strategies.stream().collect(Collectors.toMap(Strategy::getType, strategy -> strategy));
        
        /* 等同上面 map = new HashMap<>(); for (Strategy strategy : strategies) { map.put(strategy.getType(), strategy); }*/
    }

    public static class Holder {
        public static StrategyFactory instance = new StrategyFactory();
    }

    public static StrategyFactory getInstance() {
        return Holder.instance;
    }

    public Strategy get(Integer type) {
        return map.get(type);
    }
}
複製代碼

靜態內部類單例,單例模式實現的一種,不是本文重點,如不瞭解,能夠自行 google

咱們再着手建立一個 StrategyFactory 工廠類。StrategyFactory 這裏我使用的是靜態內部類單例,在構造方法的時候,初始化好 須要的 Strategy,並把 list 轉化爲 map。 這裏 轉化就是「靈魂」所在。

toMap

咱們先來看看 Java8 語法中的小技巧。

一般狀況下,咱們遍歷 List,手動put到 Map 中。

--------------  before -----------------

map = new HashMap<>();
for (Strategy strategy : strategies) {
    map.put(strategy.getType(), strategy);
}

--------------  after Java8 -----------------

map = strategies.stream().collect(Collectors.toMap(Strategy::getType, strategy -> strategy));
複製代碼

toMap 第一個參數是一個Function,對應 Map 中的 key,第二個參數也是一個Function,strategy -> strategy, 左邊strategy 是遍歷 strategies 中的每個strategy,右邊strategy則是 Map 對應 value 值。

如果不瞭解 Java8 語法的朋友,強烈建議看 《Java8 實戰》,書中詳細的介紹了 Lambda表達式、Stream等語法。

效果

private static double getResult(long money, int type) {

    if (money < 1000) {
        return money;
    }

    Strategy strategy = StrategyFactory.getInstance().get(type);
    
    if (strategy == null){
        throw new IllegalArgumentException("please input right type");
    }

    return strategy.compute(money);
}
複製代碼

至此,經過一個工廠類,在咱們在 getResult()調用的時候,根據傳入 type,便可獲取到 對應 Strategy

再也沒有可怕的 if-else 語句。

完結撒花撒花 : )

後續

後續代碼優化上,如果 Java 項目,能夠嘗試使用自定義註解,註解 Strategy 實現類。

這樣能夠簡化原來需在工廠類 List 添加一個 Stratey 策略

最後

以上就是我在開發中遇到複雜的 if-else 語句「優雅處理」思路,若有不妥,歡迎你們一塊兒交流學習。

相關文章
相關標籤/搜索