行為參數(shù)化

  • 行為參數(shù)化
    幫助你處理頻繁變更的需求的一種開發(fā)模式

篩選蘋果的例子

初試牛刀
  • 選擇綠色的蘋果
private List<Apple> inventory;

    @Before
    public void init() {
        inventory = asList(new Apple("red", 5), new Apple("green", 5), new Apple("red", 7));
    }

    /**
     * 過濾出青蘋果
     */
    @Test
    public void filterApple() {
        selectApple();
    }
    private void selectApple() {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (apple.getColor().equals("green")) {
                result.add(apple);
            }
        }
    }

如果說有一天需求改變了,需要選擇出紅蘋果怎么辦呢?
你可能認為:把if改一下,copy一份不就好了嘛!這個確實能夠解決當前問題,但是,第一:這個方案不優(yōu)雅,如果客戶要求選擇重量咋辦,或者后面用戶還會提各種需要怎么辦?這個程序的擴展性太差了。
第二:存在很多冗余的代碼,不易閱讀。

再展身手
  • 選擇青蘋果或者紅蘋果
 /**
     * 根據(jù)顏色過濾蘋果
     */
    @Test
    public void selectApple(String color) {
        selectWithColor(color);
    }
    private void selectWithColor(String color) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (apple.getColor().equals(color)) {
                result.add(apple);
            }
        }
    }

主要就完美了嗎?如果需要變成根據(jù)重量過濾怎么辦呢?難道你還打算寫一個根據(jù)重量過濾的?那要是即根據(jù)顏色又根據(jù)重量過濾怎么辦呢?你難道還有根據(jù)兩個參數(shù)去判斷,那代碼也太混亂了,一個方法不是去做一件事,閱讀起來也晦澀難懂。
那應該怎么做呢?請看參數(shù)行為化。

小小突破
  • 對行為進行抽象
public interface ApplePredicate {
    /**
     * 選擇蘋果
     *
     * @param apple
     * @return
     */
    boolean test(Apple apple);
}

抽象行為,本例是測試蘋果,具體怎么測試無需關心。有不同的子類去實現(xiàn)。

  • 對抽象行為的不同實現(xiàn)
public class ColorApplePredicate implements ApplePredicate {
    /**
     * 根據(jù)顏色過濾蘋果
     *
     * @param apple
     * @return
     */
    @Override
    public boolean test(Apple apple) {
        return apple.getColor().equals("green");
    }
}
public class WeightApplePredicate implements ApplePredicate {
    /**
     * 根據(jù)重量過濾蘋果
     *
     * @param apple
     * @return
     */
    @Override
    public boolean test(Apple apple) {
        return apple.getWeight() > 44;
    }
}

這些其實就是設計模式里面的策略模式。所謂的策略模式也就是:定義一簇算法,把它們封裝起來(稱為策略),然后在運行時選擇一個算法運行。

  • 選擇蘋果
public class StrategyApple {
    public static void main(String[] args) {
        List<Apple> inventory = asList(new Apple("red", 5), new Apple("green", 5), new Apple("red", 7));
        //根據(jù)顏色選擇蘋果
        List<Apple> apples = selectStrategyApple(inventory, new ColorApplePredicate());
        //根據(jù)重量選擇蘋果
        List<Apple> appleList = selectStrategyApple(inventory, new WeightApplePredicate());

    }

    /**
     * @param inventory 蘋果集合
     * @param predicate 操作的策略  或者是謂詞
     * @return
     */
    public static List<Apple> selectStrategyApple(List<Apple> inventory, ApplePredicate predicate) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (predicate.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }
}

試想一下,如果用戶又加了需求,需要選擇顏色加重量或者其他的等等,我們只需要添加一種策略就可以輕松搞定,不需要沒用的copy,也不需要改動代碼的主體。
這真的就是最完美的了嗎?還有優(yōu)化的空間嗎?
在上面這段代碼里我們可以看到,真正重要的是test這段代碼,但令人遺憾的是它必須通過ApplePredicate來傳遞這種行為,也就是這種行為包裹在了ApplePredicate對象里面,而不是真正的傳遞行為。我們想一下lambda是實現(xiàn)的。

//lambda
        List<Apple> lambdas = selectStrategyApple(inventory, apple -> apple.getColor().equals("green"));
        List<Apple> lambdastwo = selectStrategyApple(inventory, apple -> apple.getWeight() > 4);
        List<Apple> lambdasthree = selectStrategyApple(inventory,
            apple -> apple.getWeight() > 4 || apple.getColor().equals("green"));

從上面這段代碼我們可以看出,我們是真的把一段代碼,一種行為,作為參數(shù)傳遞過去了。代碼清新,易于閱讀,同時還少了很多沒必要的中間變量。

最后一次優(yōu)化

從目前的代碼來看還是只能使用蘋果,要是換成梨子怎么辦呢?不要告訴我copy一份,那要是再換成其他的呢?這也說明我們還有抽象的空間。

   /**
     * 抽象處理
     *
     * @param inventory
     * @param predicate 操作的策略  或者是謂詞
     * @return
     */
    public static <T> List<T> selectStrategyT(List<T> inventory, Predicate<T> predicate) {
        List<T> result = new ArrayList<>();
        for (T t : inventory) {
            if (predicate.test(t)) {
                result.add(t);
            }
        }
        return result;
    }
說明一下 static <T> 不是返回值,表示傳入?yún)?shù)有泛型
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容