用Java動態代理類實現記憶功能

來源:互聯網
上載者:User

記憶是衍生自Lisp,Python,和Perl等過程性語言的一種設計模式,它可以對前次的計算結果進行記憶。 一個實現了記憶功能的函數, 帶有顯式的cache, 所以, 已經計算過的結果就能直接從cache中獲得, 而不用每次都進行計算.

記憶能顯著的提升大計算量代碼的效率. 而且是一種可重用的方案.

本文闡述了在Java中使用這一模式的方法,並提供了一個可以提供上述功能的"記憶類":

Foo foo = (Foo) Memoizer.memoize(new FooImpl());

這裡,Foo是一個介面,它含有的方法是需要記憶的.FooImpl是Foo的一個實現.foo是Foo的一個引用.方法與FooImpl基本相同,區別在於Foo返回的值,會被緩衝起來.單個記憶類的優點在於為任何類添加記憶功能是很簡單的:定義一個包含需要記憶的方法的介面,然後調用memoize來實現一個執行個體.

為了理解記憶類是怎麼實現的,我們將分幾步來解釋.首先,我解釋一下為何緩衝能夠在需要它的類中實現.然後,我測試一下如何為一個特定的類添加緩衝封裝器.最後,我解釋一下如何才能使得一個緩衝封裝器能夠通用於任意的類.

為大計算量的程式添加緩衝

作為一個大計算配量序的例子,我們考慮PiBinaryDigitsCalculator這個例子-計算位元據pi.僅有的public方法calculateBinaryDigit帶有一個參數:整數n,代表需要精確到的位元.例如,1000000,將會返回小數點後的一百萬位,通過byte值返回-每位為0或者1.

public class PiBinaryDigitsCalculator {
/**
* Returns the coefficient of 2^n in the binary
* expansion of pi.
* @param n the binary digit of pi to calculate.
* @throws ValidityCheckFailedException if the validity
* check fails, this means the implementation is buggy
* or n is too large for sufficient precision to be
* retained.
*/
public byte calculateBinaryDigit(final int n) {
return runBBPAlgorithm(n);
}
private byte runBBPAlgorithm(final int n) {
// Lengthy routine goes here ...
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.