java懶惰評(píng)估實(shí)現(xiàn)方法
惰性評(píng)估是將表達(dá)式的評(píng)估延遲到需要時(shí)才進(jìn)行的過程。Java是嚴(yán)格的立即賦值評(píng)估。
可以使用lambda表達(dá)式和高階函數(shù)將其重寫為延遲評(píng)估的版本。
2、實(shí)例public class LazySample { public static void main(String[] args) {//這是一個(gè)lambda表達(dá)式,表現(xiàn)為閉包UnaryOperator<Integer> add = t -> { System.out.println('executing add'); return t + t;}; //這是一個(gè)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)); } //這是一個(gè)高階函數(shù) static <T, R> R addOrMultiply( boolean add, Function<T, R> onAdd, Function<T, R> onMultiply, T t ) {// Java的?會(huì)懶惰計(jì)算表達(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懶惰評(píng)估實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)java懶惰評(píng)估如何實(shí)現(xiàn)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動(dòng)態(tài)(可拖動(dòng)控件大小)布局控件QSplitter詳細(xì)使用方法與實(shí)例2. vue跳轉(zhuǎn)頁面常用的幾種方法匯總3. 父div高度不能自適應(yīng)子div高度的解決方案4. react拖拽組件react-sortable-hoc的使用5. CSS清除浮動(dòng)方法匯總6. 不要在HTML中濫用div7. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)8. XML 非法字符(轉(zhuǎn)義字符)9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. ASP動(dòng)態(tài)include文件
