Java8提出了三個(gè)新概念:流處理瓷马、行為參數(shù)化、并行處理膝宁。
目錄
什么是行為參數(shù)化皂贩?
行為參數(shù)化的好處是什么?
應(yīng)對(duì)不斷變化的需求的案例?
1. 什么是行為參數(shù)化昆汹?
行為是一個(gè)動(dòng)詞明刷,指的是舉止動(dòng)作;參數(shù)是個(gè)名稱满粗,是一個(gè)變量辈末;將一個(gè)“舉止動(dòng)作”作為參數(shù),傳遞給方法映皆。
那么行為參數(shù)化就是一個(gè)方法接受多個(gè)不同的行為作為參數(shù)挤聘,并在內(nèi)部使用它們,完成不同的行為能力捅彻。
2. 行為參數(shù)化的好處是什么组去?
行為參數(shù)化可以讓代碼更好的應(yīng)用不斷變化的需求,減少未來的工作量步淹,減少冗余的代碼从隆。
所謂傳遞代碼,就是將新行為作為參數(shù)傳遞給方法缭裆。在Java8之前需要為接口聲明許多只用一次的實(shí)體類键闺,實(shí)現(xiàn)起來很啰嗦。在Java8之前可以用匿名類來減少這種啰嗦的代碼澈驼。
3. 應(yīng)對(duì)不斷變化的需求的案例
編寫能夠應(yīng)對(duì)變化的需求的代碼并不容易辛燥,讓我們來看一個(gè)例子,我們會(huì)逐漸改進(jìn)這個(gè)例子缝其。以展示一些讓代碼更靈活的最佳做法挎塌。
Alice是一個(gè)農(nóng)場(chǎng)的農(nóng)夫,你需要幫他實(shí)現(xiàn)一個(gè)從列表中篩選綠蘋果的功能内边,聽起來很簡單吧榴都。
3.1 小試牛刀,第一個(gè)解決方案可能是下面這樣的
public static List<Apple> filterGreenApples(List<Apple> inventory) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple : inventory) {
if ("green".equals(apple.getColor()) {
result.add(apple);
}
} return result;
}
現(xiàn)在Alice改變注意了假残,他還想要篩選紅蘋果缭贡,你該怎么做呢?簡單的解決當(dāng)大就是復(fù)制這個(gè)方法辉懒,把名字改成filterRedApples阳惹,然后更改if條件匹配紅蘋果。然而Alice想要篩選多種蘋果:淺綠色眶俩、暗紅色莹汤、黃色…這種做法就應(yīng)付不了了。一個(gè)良好的原則是在編寫類似的代碼后颠印,嘗試將其抽象化纲岭。
3.2 再展身手,把顏色作為參數(shù)
public static List<Apple> filterApplesByColor(List<Apple> inventory,
String color) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple : inventory) {
if (apple.getColor().equals(color)) {
result.add(apple);
}
}
return result;
}
Alice又跑來跟你說线罕,要是能區(qū)分輕蘋果和重蘋果就太好了止潮,重蘋果一般是150g。作為軟件工程師钞楼,你早就想到Alice可能還會(huì)更改重量喇闸,于是你是這樣解決的:
public static List<Apple> filterApplesByWeight(List<Apple> inventory,
int weight) {
List<Apple> result = new ArrayList<Apple>();
For(Apple apple:inventory){
if (apple.getWeight() > weight) {
result.add(apple);
}
}
return result;
}
解決方案不錯(cuò),但是請(qǐng)注意询件,你復(fù)制了大部分的代碼來實(shí)現(xiàn)遍歷庫存燃乍,并對(duì)每一個(gè)蘋果應(yīng)用篩選條件。這有點(diǎn)令人失望宛琅,應(yīng)為它打破了DRY(Don’t Repeat Yourself刻蟹,不要重復(fù)你自己)的軟件原則。
3.3 第三次嘗試:對(duì)你想到的每一個(gè)屬性做篩選
public static List<Apple> filterApples(List<Apple> inventory, String color,
int weight, boolean flag) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple : inventory) {
if ((flag && apple.getColor().equals(color)) ||
(!flag && apple.getWeight() > weight)) {
result.add(apple);
}
}
return result;
}
//你可以這么調(diào)用:
List<Apple> greenApples = filterApples(inventory, "green", 0, true);
List<Apple> heavyApples = filterApples(inventory, "", 150, false);
這種做法好嗎嘿辟?目前只是顏色和重量兩個(gè)屬性的判斷舆瘪,如果需要過濾掉生產(chǎn)地、形狀... 屬性呢红伦?你會(huì)有好多個(gè)重復(fù)的filter方法介陶,或一個(gè)巨大的非常復(fù)雜的方法。對(duì)與組合屬性的擴(kuò)展性好像不太友好色建。
行為參數(shù)化
讓我們后退一步來看看更高層次的抽象哺呜。一種可能的解決方案是對(duì)你的選擇標(biāo)準(zhǔn)建模:你考慮的是蘋果,需要根據(jù)Apple的某些屬性(比如綠色箕戳、重量)來返回一個(gè)boolean值某残。我們稱它為謂詞(一個(gè)返回boolean值的函數(shù)),讓我們定義一個(gè)接口為選擇標(biāo)準(zhǔn)建模陵吸。
public interface ApplePredicate {
boolean test(Apple apple);
}
現(xiàn)在你可以用ApplePredicate的多個(gè)實(shí)現(xiàn)代表不同的選擇標(biāo)準(zhǔn)了玻墅。
僅僅選出重的蘋果
public class AppleHeavyWeightPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
僅僅選出綠蘋果
public class AppleGreenColorPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return "green".equals(apple.getColor());
}
}
你可以把這些看作是filter方法的不同行為。這些行為就像是不同的策略壮虫,ApplePredicate就像是一個(gè)算法蔟澳厢。
但是环础,該怎么利用ApplePredicate的不同實(shí)現(xiàn)呢?你需要讓filterApples方法接受ApplePredicate對(duì)象剩拢,對(duì)Apple做條件篩選线得。這就是行為參數(shù)化:讓方法接受多種行為做參數(shù),并在內(nèi)部使用徐伐,來完成不同的行為贯钩。
3.4 第四次嘗試:根據(jù)抽象條件篩選
public static List<Apple> filterApples(List<Apple> inventory,
ApplePredicate p) {
List<Apple> result = new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
現(xiàn)在你把filterApples方法迭代集合的邏輯與你要應(yīng)用到集合中每個(gè)元素的行為區(qū)分開了。
現(xiàn)在Alice讓你找出所有重量超過150g的紅蘋果办素,你只需要?jiǎng)?chuàng)建一個(gè)類來實(shí)現(xiàn)ApplePredicate就行了角雷。
public class AppleRedAndHeavyPredicate implements ApplePredicate {
public boolean test(Apple apple) {
return "red".equals(apple.getColor())
&& apple.getWeight() > 150;
}
}
List<Apple> redAndHeavyApples = filterApples(inventory, new AppleRedAndHeavyPredicate());
你已經(jīng)做了一件很酷的事:filterApples方法的行為取決你通過ApplePredicate對(duì)象傳遞的代碼,換句話說性穿,你把filterApples方法的行為參數(shù)化了勺三!
請(qǐng)注意,在上一個(gè)例子中需曾,唯一重要的代碼是test方法的實(shí)現(xiàn)檩咱,由于filterApples方法只能接受對(duì)象,所以你必須把代碼包裹ApplePredicate對(duì)象里胯舷。你的做法就類似與在內(nèi)聯(lián)“傳遞代碼”刻蚯。你會(huì)在下一節(jié)中看到,通過使用Lambda桑嘶,可以直接將表達(dá)式"red".equals(apple.getColor())
&&apple.getWeight() > 150傳遞給filterApples方法炊汹,省去定義多個(gè)ApplePredicate的實(shí)現(xiàn)類,從而去掉不必要的代碼逃顶。
Java8之前是如何做的讨便?使用匿名類
3.5 第五次嘗試:使用匿名類
List<Apple> redApples = filterApples(inventory, new ApplePredicate() {
public boolean test(Apple apple) {
return "red".equals(apple.getColor());
}
});
Java8是如何做的?使用Lambda表達(dá)式
3.6 第六次嘗試:使用Lambda表達(dá)式
List<Apple> result = filterApples(inventory, (Apple apple) -> "red".equals(apple.getColor()));
匿名類與Lambda表達(dá)式的比較
匿名類:
它看起來很笨重以政,因?yàn)樗加昧撕芏嗫臻g霸褒。
讓我們覺得它用起來很讓人費(fèi)解。好的代碼應(yīng)該是一目了然的盈蛮。雖然匿名類在一定程度上改善了為一個(gè)接口聲明好幾個(gè)實(shí)體類的啰嗦問題废菱,但它仍不能令人滿意。
Lambda表達(dá)式:
不得不承認(rèn)這代碼看上去比先前干凈很多抖誉。
3.7 第七次嘗試:將List類型抽象化
public interface Predicate<T> {
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> result = new ArrayList<>();
for (T e : list) {
if (p.test(e)) {
result.add(e);
}
}
return result;
}
現(xiàn)在你可以把filter方法用在香蕉殊轴、橘子Integer或String的列表上了。
eg.
List<Apple> redApples =
filter(inventory, (Apple apple) -> "red".equals(apple.getColor()));
List<Integer> evenNumbers =
filter(numbers, (Integer i) -> i % 2 == 0);
酷不酷袒炉?你現(xiàn)在在靈活性和簡潔性之間找到了最佳的平衡點(diǎn)旁理,這在Java8之前是不能做到的!
3.8 真實(shí)的例子
用Comparator來排序
Alice想要根據(jù)蘋果的重量對(duì)庫存進(jìn)行排序(ps,Java8中我磁,List自帶了一個(gè)sort方法)我們用Collections.sort
// java.util.Comparator
public interface Comparator<T> {
public int compare(T o1, T o2);
}
inventory.sort(new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
});
用Lambda表達(dá)式的話孽文,看起來是這樣的:
inventory.sort(
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
用 Runnable 來執(zhí)行代碼塊
// java.lang.Runnable
public interface Runnable{
public void run();
}
Thread t = new Thread(new Runnable() {
public void run(){
System.out.println("Hello world");
}
});
用Lambda表達(dá)式的話驻襟,看起來是這樣的:
Thread t = new Thread(() -> System.out.println("Hello world"));
看完這個(gè)案例,你對(duì)行為參數(shù)化有所了解了嗎芋哭???