我們需要從一堆蘋果中按顏色挑出符合要求的蘋果瓮顽。最初翔横,我們可能會按不同的條件寫幾個相似的方法來做這件事
- Version 1
public List<Apple> filterGreenApples(List<Apple> inventory){
List<Apple> result = new ArrayList<>();
for(Apple apple: inventory){
if("green".equals(apple.getColor())){
result.add(apple);
}
}
return result;
}
public List<Apple> filterRedApples(List<Apple> inventory){
List<Apple> result = new ArrayList<>();
for(Apple apple: inventory){
if("red".equals(apple.getColor())){
result.add(apple);
}
}
return result;
}
好像重復(fù)的代碼有點太多了癞谒,只有顏色的判斷條件不同而已藤滥,我們做一個重構(gòu)
- Version 2
public List<Apple> filterApplesByColor(List<Apple> inventory, String color){
List<Apple> result = new ArrayList<>();
for(Apple apple: inventory){
if(apple.getColor().equals(color)){
result.add(apple);
}
}
return result;
}
單單顏色不能滿足我們的需求鳖粟,我們還希望按重量來過濾
- Version 3
public List<Apple> filterApplesBiggerThanWeight(List<Apple> inventory, int weight){
List<Apple> result = new ArrayList<>();
for(Apple apple: inventory){
if(apple.getWeight() > weight ){
result.add(apple);
}
}
return result;
}
顏色版本和重量版本差的只是判斷條件,其他部分依然是相同的拙绊,同理對其他屬性來說情況也是一樣的向图,所以我們引入行為參數(shù)化。
- Version 4
public interface ApplePredicate{
public boolean test(Apple apple);
}
public List<Apple> filterApples(List<Apple> inventory, ApplePredicate p){
List<Apple> result = new ArrayList<>();
for(Apple apple: inventory){
if(p.test() ){
result.add(apple);
}
}
return result;
}
public AppleGreenColorPredicate implements ApplePredicate{
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}
public AppleWeightPredicate implements ApplePredicate{
public boolean test(Apple apple){
return apple.getWeight() > 150;
}
}
行為參數(shù)化解決了我們的主要問題标沪,但是實現(xiàn)看起來有點啰嗦榄攀,我們要實現(xiàn)AppleGreenColorPredicate,AppleWeightPredicate等等金句,有許多重復(fù)的類定義代碼檩赢。Java 7時代我們使用匿名類來減少一部分代碼
- Version 5
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
public boolean test(Apple apple){
return "red".equals(apple.getColor());
}
}
到了Java 8我們可以使用Lambda來替代不易使用的匿名類
- Version 6
List<Apple> redApples = filterApples(inventory, apple -> "red".equals(apple.getColor()))
這樣就簡潔很多了。