1. 程式人生 > >Apache commons 之 Collections :Predicate

Apache commons 之 Collections :Predicate

Predicate是Commons Collections中定義的一個介面,可以在org.apache.commons.collections包中找到。其中定義的方法簽名如下:

public booleanevaluate(Object object)

它以一個Object物件為引數,處理後返回一個boolean值,檢驗某個物件是否滿足某個條件。其實這個Predicate以及上一篇筆記提到的Comparator還有我們即將看到的Transformer和Closure等都有些類似C/C++中的函式指標,它們都只是提供簡單而明確定義的函式功能而已。

跟其他組類似,Commons Collections也提供了一組定義好的Predicate類供我們使用,這些類都放在org.apache.commons.collections.functors包中。當然,我們也可以自定義Predicate,只要實現這個Predicate介面即可。在Commons Collections中我們也可以很方便使用的一組預定義複合Predicate,我們提供2個或不定數量個Predicate,然後交給它,它可以幫我們處理額外的邏輯,如AndPredicate處理兩個Predicate,只有當兩者都返回true它才返回true;AnyPredicate處理多個Predicate,當其中一個滿足就返回true,等等。

看看具體的程式碼中如何使用這些Predicate吧:

packagetest.ffm83.commons.collections;

importorg.apache.commons.collections.Predicate;

importorg.apache.commons.collections.PredicateUtils;

importorg.apache.commons.collections.functors.InstanceofPredicate;

importorg.apache.commons.collections.functors.NotNullPredicate;

importorg.apache.commons.lang.BooleanUtils;

importorg.apache.commons.lang.StringUtils;

public classPredicateUsage {

   public static voidmain(String[] args) {

      demoPredicates();

   }

   public static void demoPredicates() {

      System.out.println(StringUtils.center("demoPredicates ", 40, "="

));

      Predicatep1 = new InstanceofPredicate(String.class);

      Predicatep2 = NotNullPredicate.getInstance();

      Predicatep3 = new Predicate() {

         public booleanevaluate(Object obj) {

            Stringstr = (String) obj;

            return StringUtils.isAlphanumeric(str)&& str.length() >= 6

                   &&str.length() <= 10;

         }

      };

      Predicatep4 = PredicateUtils

            .allPredicate(newPredicate[] { p1, p2, p3 });

      Stringinput = "ABCD1234";

      Object[]raw = new Object[] { "Is'", input, "' a valid input? ",

            BooleanUtils.toStringYesNo(p4.evaluate(input)),"." };

      System.out.println(StringUtils.join(raw));

      System.out.println(StringUtils.repeat("=",40));

   }

}

輸出結果如下:

============ demoPredicates ============

Is 'ABCD1234' a valid input? yes.

========================================

這裡面我首先定義了3個簡單的Predicate,p1判斷物件是否為String的例項,p2判斷是否物件為null,p3是自定義的,判斷是否為數字字母的組合,並且長度在6~10字元。然後我用AllPredicate將它們組合到一起,成為p4,當p1、p2、p3都滿足時,p4的evaluate方法才返回true。利用Predicate我們可以把判斷true或false的邏輯從特定的業務程式碼分離出來,以後我們重用也好,重新組裝也好,都是很方便的。