我知道这个http://onjava.com/pub/a/onjava/2003/08/20/memoization.html但还有别的吗?
问问题
20139 次
3 回答
22
要记住没有参数的函数,请使用 Guava 的Suppliers.memoize(Supplier)
. 对于带参数的函数,使用CacheBuilder.build(CacheLoader)
参数值对象作为键。
于 2013-06-03T09:39:09.350 回答
17
例子:
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));
}
}
}
于 2010-09-02T04:17:44.383 回答
15
使用简单的类型安全 Java,记忆化也很容易。
您可以使用以下可重用类从头开始。
我将它们用作缓存,其生命周期是 webapp 上的请求。
MapMaker
如果您需要驱逐策略或同步等更多功能,当然可以使用 Guava 。
如果您需要记忆具有许多参数的方法,只需将参数放在具有两种技术的列表中,然后将该列表作为单个参数传递。
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);
于 2010-09-02T05:36:56.200 回答