增加代碼的靈活性
有條件if的延遲執行
public static void main(String[] args) {
// 即使內部不調用genString,這里已經調用了genString
print(false, genString());
// genString的調用延遲到內部supplier.get()時候調用
print(false, () -> genString());
}
// 通過Supplier方式實現有條件的延遲加載
public static void print(boolean b, Supplier<String> genString) {
if (b)
System.out.println(genString.get());
}
public static void print(boolean b, String s) {
if (b)
System.out.println(s);
}
public static String genString() {
System.out.println("genString");
return "string";
}
環繞執行模式
// 先定義一個函數式接口
@FunctionalInterface
public interface BufferedReaderProcessor {
String process(...);
}
// 定義模板方法, 之前的函數接口作為參數
public static String processFile(BufferedReaderProcessor p) {
// 開頭一堆代碼, 比如打開文件
...
// 容易變化的地方調用函數接口的方法
p.process(br);
// 結尾一堆代碼,比如關閉文件
...
}
// 不同的場景通過傳遞不同的業務邏輯lambda,只需要一份模板即可
String oneLine = processFile((BufferedReader br) -> ...);
String twoLine = processFile((BufferedReader br) -> ...);
重構設計模式
策略模式
// 直接new接口,傳入lambda實現邏輯,相當于new了實現類
Validator numericValidator = new Validator((String s) -> ...);
Validator lowerValidator = new Validator((String s) -> ...);
boolean b1 = numericValidator.validate("...");
boolean b2 = lowerValidator.validate("...");
模板模式
// 定義模板方法,增加一個Consumer參數,負責變動部分邏輯(當然根據實際場景選擇合適類型的函數式接口,本質是參數化行為)
public void processTemplate(int id, Consumer<Code> logicCode) {
XXX xxx = getXXXX(id); // 固定邏輯的模板部分
logicCode.accept(xxx); // 需要變化的部分使用comsumer.accept調用
closeXXX();
}
觀察者模式
// 使用lambda表達式,代替繁瑣的new 實例化接口對象
f.registerObserver((String tweet) -> {...});
責任鏈模式
// handler用UnaryOperation表示
UnaryOperation<String> headerProcessing = (String text) -> "From Raoul ... ";
UnaryOperation<String> spellCheckerProcessing = (String text) -> text.replaceAll(...);
// 通過Function串聯起handler
Function<String, String> pipeline = headerProcessing.andThen(spellCheckerProcessing);
String result = pipeline.apply("...");
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。