- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- java懶惰評估實(shí)現方法
惰性評估是將表達式的評估延遲到需要時(shí)才進(jìn)行的過(guò)程。Java是嚴格的立即賦值評估。
可以使用lambda表達式和高階函數將其重寫(xiě)為延遲評估的版本。
public class LazySample { public static void main(String[] args) { //這是一個(gè)lambda表達式,表現為閉包 UnaryOperator<Integer> add = t -> { System.out.println("executing add"); return t + t; }; //這是一個(gè)lambda表達式,表現為閉包 UnaryOperator<Integer> multiply = t -> { System.out.println("executing multiply"); return t * t; }; //傳遞Lambda閉包而不是普通函數 System.out.println(addOrMultiply(true, add, multiply, 4)); System.out.println(addOrMultiply(false, add, multiply, 4)); } //這是一個(gè)高階函數 static <T, R> R addOrMultiply( boolean add, Function<T, R> onAdd, Function<T, R> onMultiply, T t ) { // Java的?會(huì )懶惰計算表達式,因此僅執行所需的方法 return (add ? onAdd.apply(t) : onMultiply.apply(t)); } }
實(shí)例擴展:
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í)現方法的文章就介紹到這了,更多相關(guān)java懶惰評估如何實(shí)現內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站