java懶惰評估實(shí)現(xiàn)方法
惰性評估是將表達(dá)式的評估延遲到需要時才進(jìn)行的過程。Java是嚴(yán)格的立即賦值評估。
可以使用lambda表達(dá)式和高階函數(shù)將其重寫為延遲評估的版本。
2、實(shí)例public class LazySample { public static void main(String[] args) {//這是一個lambda表達(dá)式,表現(xiàn)為閉包UnaryOperator<Integer> add = t -> { System.out.println('executing add'); return t + t;}; //這是一個lambda表達(dá)式,表現(xiàn)為閉包UnaryOperator<Integer> multiply = t -> { System.out.println('executing multiply'); return t * t;};//傳遞Lambda閉包而不是普通函數(shù)System.out.println(addOrMultiply(true, add, multiply, 4));System.out.println(addOrMultiply(false, add, multiply, 4)); } //這是一個高階函數(shù) static <T, R> R addOrMultiply( boolean add, Function<T, R> onAdd, Function<T, R> onMultiply, T t ) {// Java的?會懶惰計算表達(dá)式,因此僅執(zhí)行所需的方法return (add ? onAdd.apply(t) : onMultiply.apply(t)); }}
實(shí)例擴(kuò)展:
public class SingleLock<V> implements Lazy<V> { private Callable<V> codeBlock; private V value; public SingleLock(Callable<V> codeBlock) {this.codeBlock = codeBlock; } @Override public synchronized V get() {if (value == null) { setValue();}return value; } private void setValue() {try { value = codeBlock.call();} catch (Exception e) { throw new RuntimeException(e);} } }
到此這篇關(guān)于java懶惰評估實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)java懶惰評估如何實(shí)現(xiàn)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python sorted排序方法如何實(shí)現(xiàn)2. Python基于requests實(shí)現(xiàn)模擬上傳文件3. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車4. windows服務(wù)器使用IIS時thinkphp搜索中文無效問題5. python利用opencv實(shí)現(xiàn)顏色檢測6. Python文本文件的合并操作方法代碼實(shí)例7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效9. asp讀取xml文件和記數(shù)10. Python獲取B站粉絲數(shù)的示例代碼
