用Lambda重構責任模式鏈
責任鏈模式是建立處理物件鏈(例如一系列操作)的通用解決方案。一個處理物件可以做一些工作並將結果傳遞給另一個物件,然後該物件也做一些工作並將其傳遞給另一個處理物件,依此類推。
責任鏈模式:不使用Lambda表示式
步驟1:通常,通過定義表示處理物件的抽象類來實現該模式,該處理物件定義用於跟蹤後繼的欄位。一旦完成工作, 處理物件將其工作交給其繼任者。在程式碼中它看起來像這樣:
<b>public</b> <b>abstract</b> <b>class</b> ProcessingObject<T> { <b>protected</b> ProcessingObject<T> successor; <b>public</b> <b>void</b> setSuccessor(ProcessingObject<T> successor) { <b>this</b>.successor = successor; } <b>public</b> T handle(T input) { T r = handleWork(input); <b>if</b> (successor != <b>null</b>) { <b>return</b> successor.handle(r); } <b>return</b> r; } <b>abstract</b> <b>protected</b> T handleWork(T input); }
方法handle提供瞭如何處理一項工作的概述。通過繼承類ProcessingObject併為方法handleWork提供實現,可以建立不同型別的處理物件 。
讓我們看一個如何使用這種模式的例子。您可以建立兩個處理物件進行一些文字處理:
<b>public</b> <b>class</b> HeaderTextProcessing <b>extends</b> ProcessingObject<String> { <b>public</b> String handleWork(String text) { <b>return</b> <font>"From Raoul, Mario and Alan: "</font><font> + text; } } <b>public</b> <b>class</b> SpellCheckerProcessing <b>extends</b> ProcessingObject<String> { <b>public</b> String handleWork(String text) { <b>return</b> text.replaceAll(</font><font>"labda"</font><font>, </font><font>"lambda"</font><font>); } } </font>
讓我們編寫程式碼來測試上面沒有lambda表示式的程式碼:
<b>public</b> <b>static</b> <b>void</b> main(String[] args) { ProcessingObject<String> p1 = <b>new</b> HeaderTextProcessing(); ProcessingObject<String> p2 = <b>new</b> SpellCheckerProcessing(); p1.setSuccessor(p2); String result1 = p1.handle(<font>"Aren't labdas really sexy?!!"</font><font>); System.out.println(result1); } </font>
責任鏈模式:使用Lambda表示式
通過使用lambda表示式,我們可以避免建立子類來實現handleWork()方法。我們可以將處理物件表示為Function <String,String> 的例項, 或者更確切地說是 UnaryOperator <String> 。要連結它們,我們只需要使用andThen 方法來組合這些函式 。
<b>public</b> <b>static</b> <b>void</b> main(String[] args) { <font><i>// First processing object</i></font><font> UnaryOperator<String> headerProcessing = (String text) -> </font><font>"From Raoul, Mario and Alan: "</font><font> + text; </font><font><i>//Second processing object</i></font><font> UnaryOperator<String> spellCheckerProcessing = (String text) -> text.replaceAll(</font><font>"labda"</font><font>, </font><font>"lambda"</font><font>); </font><font><i>// Compose the two functions resulting in a chain of operations.</i></font><font> Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing); String result2 = pipeline.apply(</font><font>"Aren't labdas really sexy?!!"</font><font>); System.out.println(result2); } </font>