回答
記憶化也很容易用普通簡單類型安全的Java。
您可以從頭開始使用以下可重用類。
我使用這些作爲其生命週期是Web應用程序的請求的緩存。
如果您需要驅逐策略或更多功能(如同步),當然可以使用Guava MapMaker
。
如果您需要記憶具有多個參數的方法,只需將這兩個參數放入列表中,然後將該列表作爲單個參數傳遞。
abstract public class Memoize0<V> {
//the memory
private V value;
public V get() {
if (value == null) {
value = calc();
}
return value;
}
/**
* will implement the calculation that
* is to be remembered thanks to this class
*/
public abstract V calc();
}
abstract public class Memoize1<P, V> {
//The memory, it maps one calculation parameter to one calculation result
private Map<P, V> values = new HashMap<P, V>();
public V get(P p) {
if (!values.containsKey(p)) {
values.put(p, calc(p));
}
return values.get(p);
}
/**
* Will implement the calculations that are
* to be remembered thanks to this class
* (one calculation per distinct parameter)
*/
public abstract V calc(P p);
}
,這是像這樣使用
Memoize0<String> configProvider = new Memoize0<String>() {
@Override
public String calc() {
return fetchConfigFromVerySlowDatabase();
}
};
final String config = configProvider.get();
Memoize1<Long, String> usernameProvider = new Memoize1<Long, String>() {
@Override
public String calc(Long id) {
return fetchUsernameFromVerySlowDatabase(id);
}
};
final String username = usernameProvider.get(123L);
實施例:
import java.math.BigInteger;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class Fibonacci {
private static final LoadingCache<Integer, BigInteger> CACHE
= CacheBuilder.newBuilder().build(CacheLoader.from(Fibonacci::fib));
public static BigInteger fib(int n) {
Preconditions.checkArgument(n >= 0);
switch (n) {
case 0:
return BigInteger.ZERO;
case 1:
return BigInteger.ONE;
default:
return CACHE.getUnchecked(n - 1).add(CACHE.getUnchecked(n - 2));
}
}
}
MapMaker現在已被棄用,以支持CacheBuilder:https://code.google.com/p/guava-libraries/wiki/MapMakerMigration – dzieciou 2013-11-08 19:55:20
@dzieciou我終於更新了代碼,使其與最新的Guava(18.0當前寫作時間)。這一次,它已經過測試! – 2015-03-22 05:35:01
爲了memoize的功能,而無需參數,使用番石榴的Suppliers.memoize(Supplier)
。對於帶參數的函數,使用CacheBuilder.build(CacheLoader)
和參數值對象作爲鍵。
- 1. 壓縮技術有哪些?
- 2. 更大的項目有哪些技術?
- 3. Quake Live背後的技術有哪些?
- 4. 要使用哪些Java EE技術?
- 5. ADO.NET包含哪些技術?
- 6. 那裏有哪些p2p技術?
- 7. 在lucene中使最新內容相關的技術有哪些?
- 8. 聲音流中的詞彙識別技術有哪些?
- 9. 有條件加載內容的技術有哪些?
- 10. ASP.NET爲您的客戶提供API有哪些好的技術?
- 11. 哪些媒體查詢技術使用
- 12. 映射聲波涉及哪些技術?
- 13. 製作Mozilla Firefox涉及哪些技術?
- 14. 10。我應該使用哪些技術?
- 15. 哪些是「X」的技術術語「爲X ...」
- 16. java中的最新技術
- 17. 在網絡上超快速開發的技術有哪些?
- 18. 豐富的UI桌面應用程序有哪些技術?
- 19. 有哪些方法可以利用SecurID和類似的技術?
- 20. 。後端技術有哪些可能的選擇?
- 21. iPhone:哪些是加速藍牙最有用的技術?
- 22. 哪些內存管理技術在哪些情況下更好?
- 23. 應該在遠程服務器上使用哪些Java技術?
- 24. 哪些java技術用於開發android應用程序?
- 25. 在哪些技術上實現了Java RMI?
- 26. 哪些技術用於.net中的中間件服務器?
- 27. 在聯網的計算機中分佈的軟件組件之間的通信有哪些不同的技術?
- 28. Java WebService技術
- 29. 爲幻燈片加載圖像有哪些技術?
- 30. 提供訂閱服務有哪些技術?
本示例通過代理記錄對象的所有方法。但是,典型的記憶是當時的一個功能。當你不想記憶對象的所有方法時,這種代理技術會很煩人。 – lacroix1547 2010-09-02 05:45:31