2014-01-15 15 views
1

G'day同志。我有個問題。提供字段存取方法作爲參數

我有兩個方法是完全重複,他們正在訪問不同的領域。我無法通過字段值作爲參數,因爲訪問需要一個循環(簡化的例子)內的地方:

public final class Thing { 

     ImmutableList<Box> boxes; 

     public int getNumberOfApples() { 
      int total = 0; 
      for (Box box : boxes) { 
       total += box.getApplesCount(); 
      } 
      return total; 
     } 

     public int getNumberOfPears() { 
      int total = 0; 
      for (Box box : boxes) { 
       total += box.getPearsCount(); 
      } 
      return total; 
     } 
    } 

我可以把我的水果成地圖,並通過字段名作爲參數,但它看起來髒髒的,我我對現在的班級作文很滿意。所以問題是 - 我如何重構我的代碼以獲得單一類型的方法:

public int getNumberOfFruit(SomethingMagic) { 
    moreMagic; 
    return total; 
} 

Cheerio。

+0

開關狀況,或者如果條件...傳遞一個字符串即「蘋果」或「梨」到你的功能,使它一般 - getNumberOfFruit(String fruitName).. if(type.equals(「apple」))doSomething ... if(type.equals(「pear」))doSomethingElse .. – TheLostMind

+0

想到這一點,但仍然看起來醜陋。如果我得到一百種水果,會怎麼樣? – Rince

回答

6

好了,你可以有這樣的:

public interface Function<In, Out> { 
    Out apply(In input); 
} 

然後:

public int getCount(Function<Box, Integer> projection) { 
    int total = 0; 
    for (Box box : boxes) { 
     total += projection(box); 
    } 
    return total; 
} 

眼下構建是投影將是醜陋的,例如

int pears = thing.getCount(new Function<Box, Integer>() { 
    @Override public Integer apply(Box input) { 
     return box.getPearsCount(); 
    } 
}); 

但在Java 8,這將是更簡單的用lambda表達式:

int pears = thing.getCount(box -> box.getPearsCount()); 

注意,拉斐爾·羅西的回答是稍微通過使接口不通用比我具體。這意味着它可以更有效率,因爲不需要計數 - 但是可重用性較差,當然。您決定使用哪種方法是一個判斷調用,這在很大程度上取決於您的實際使用情況。

+0

正是我在找的。謝謝喬恩! – Rince

1

我會建議功能的做法。定義一個函數進入你的getNumberOfFruit,它將檢索正確水果的數量。喜歡的東西:

public interface FruitCounter { 
    int apply(Box box); 
} 

public int getNumberOfFruit(FruitCounter counter) { 
    int total = 0; 
    for (Box box : boxes) { 
     total += counter.apply(box); 
    } 
    return total; 
} 

然後通過適當的執行數蘋果或梨:

int numOfApples theThing.getNumberOfFruit(new FruitCounter() { 
    @Override 
    public int apply(Box box) { 
     return box.getApplesCount(); 
    }); 

int numOfPears theThing.getNumberOfFruit(new FruitCounter() { 
    @Override 
    public int apply(Box box) { 
     return box.getPearsCount(); 
    }); 
+0

四分鐘遲到:D – Rince

相關問題