Java中的memoization有哪些不同的技术? [英] What are the different techniques for memoization in Java?
问题描述
我知道这个 http://onjava.com /pub/a/onjava/2003/08/20/memoization.html 但还有其他什么吗?
I know of this one http://onjava.com/pub/a/onjava/2003/08/20/memoization.html but is there anything else?
推荐答案
使用普通的简单类型安全Java,记忆也很容易。
Memoization is also easy with plain simple typesafe Java.
您可以从头开始使用以下可重用的类。
You can do it from scratch with the following reusable classes.
我将这些用作缓存,其生命周期是webapp上的请求。
I use these as caches whose lifespan are the request on a webapp.
当然使用Guava MapMaker
如果您需要驱逐策略或更多功能,如同步。
Of course use the Guava MapMaker
if you need an eviction strategy or more features like synchronization.
如果你需要记忆一个包含许多参数的方法,只需将这些参数放在一个列表中,然后将该列表作为单个参数传递。
If you need to memoize a method with many parameters, just put the parameters in a list with both techniques, and pass that list as the single parameter.
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);
这篇关于Java中的memoization有哪些不同的技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!