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.(演算法可以參考: http://www.cecm.sfu.ca/~pborwein/PAPERS/P123.pdf)
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 ...
}

}

最簡單直接的方法來緩衝傳回值可以通過修改這個類來實現:添加一個Map來儲存之前計算得到的值,如下:
import java.util.HashMap;

public class PiBinaryDigitsCalculator {

private HashMap cache = new HashMap();

public synchronized byte calculateBinaryDigit(
final int n) {

final Integer N = new Integer(n);
Byte B = (Byte) cache.get(N);
if (B == null) {
byte b = runBBPAlgorithm(n);
cache.put(N, new Byte(b));
return b;
} else {
return B.bytevalue();
}
}

private byte runBBPAlgorithm(final int n) {
// Lengthy routine goes here ...
}
}


calculateBinaryDigit方法首先會檢查HashMap裡面是否緩衝了這個關鍵字-參數n,如果找到了,就直接返回這個值.否則,就會進行這個冗長的計算,並將結果儲存到緩衝裡面.在添加進HashMap的時候,在原始類型和對象之間還要進行小小的轉換.
儘管這個方法是可行的,但是有幾個缺點.首先,進行緩衝的代碼和正常的演算法代碼不是顯著分開的.一個類,不僅負責進行計算,也要負責進行維護快取資料.這樣,要進行一些測試就會顯得很困難.比如,不能寫一個測試程式來測試這個演算法持續地返回相同的值,因為,從第二次開始,結果都是直接從cache中獲得了.
其次,當緩衝代碼不再需要,移除它會變得困難,因為它和演算法塊地代碼是緊密結合在一起的.所以,要想知道緩衝是否帶來了很高的效率提升也是很困難的,因為不能寫一個測試程式是和快取資料分開的.當你改進了你的演算法,緩衝有可能失效-但是這個時候你並不知道.
第三,緩衝代碼不能被重用.儘管代碼遵從了一個普通的模式,但是都是在一個類- PiBinaryDigitsCalculator裡面.

前面兩個問題都可以通過構造一個緩衝封裝器來解決.

緩衝封裝器
通過使用Decorator模式,要分開計算代碼和緩衝代碼是很容易的.首先,定義一個介面,裡面定義基本的方法.
public interface BinaryDigitsCalculator {

public byte calculateBinaryDigit(final int n);
}



然後定義兩個實現,分別負責兩個任務:
public class PiBinaryDigitsCalculator
implements BinaryDigitsCalculator {

public byte calculateBinaryDigit(final int n) {
return runBBPAlgorithm(n);
}

private byte runBBPAlgorithm(final int n) {
// Lengthy routine goes here ...
}

}

import java.util.HashMap;

public class CachingBinaryDigitsCalculator implements
BinaryDigitsCalculator {

private BinaryDigitsCalculator binaryDigitsCalculator;
private HashMap cache = new HashMap();

public CachingBinaryDigitsCalculator(
BinaryDigitsCalculator calculator) {
this.binaryDigitsCalculator = calculator;
}

public synchronized byte calculateBinaryDigit(int n) {
final Integer N = new Integer(n);
Byte B = (Byte) cache.get(N);
if (B == null) {
byte b =
binaryDigitsCalculator.calculateBinaryDigit(n);
cache.put(N, new Byte(b));
return b;
} else {
return B.bytevalue();
}
}
}


這是很之前的實現PiBinaryDigitsCalculator的一種簡單的refactored版本. CachingBinaryDigitsCalculator封裝了BinaryDigitsCalculator控制代碼,並增加了緩衝,供calculateBinaryDigit的方法調用. 這種方法提高了代碼的可讀性與可維護性. 使用者不能直接使用BinaryDigitsCalculator介面來實現演算法,所以,如果需要關閉緩衝塊,將是很容易實現的.
還有,合適的測試程式很容易寫出來.比如,我們寫一個假的BinaryDigitsCalculator實現,每次calculateBinaryDigit被調用,賦予相同的參數,返回不同的值. 這樣,我們就能測試緩衝是否工作了,因為如果每次都返回相同的值,則證明緩衝是正常工作了. 這種測試在之前那種簡單的實現是不可能的.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.