Bạn có thể sử dụng giao diện Function trong thư viện guava của Google để dễ dàng đạt được những gì bạn đang sau:
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Function;
public class MemoizerTest {
/**
* Memoizer takes a function as input, and returns a memoized version of the same function.
*
* @param <F>
* the input type of the function
* @param <T>
* the output type of the function
* @param inputFunction
* the input function to be memoized
* @return the new memoized function
*/
public static <F, T> Function<F, T> memoize(final Function<F, T> inputFunction) {
return new Function<F, T>() {
// Holds previous results
Map<F, T> memoization = new HashMap<F, T>();
@Override
public T apply(final F input) {
// Check for previous results
if (!memoization.containsKey(input)) {
// None exists, so compute and store a new one
memoization.put(input, inputFunction.apply(input));
}
// At this point a result is guaranteed in the memoization
return memoization.get(input);
}
};
}
public static void main(final String[] args) {
// Define a function (i.e. inplement apply)
final Function<Integer, Integer> add2 = new Function<Integer, Integer>() {
@Override
public Integer apply(final Integer input) {
System.out.println("Adding 2 to: " + input);
return input + 2;
}
};
// Memoize the function
final Function<Integer, Integer> memoizedAdd2 = MemoizerTest.memoize(add2);
// Exercise the memoized function
System.out.println(memoizedAdd2.apply(1));
System.out.println(memoizedAdd2.apply(2));
System.out.println(memoizedAdd2.apply(3));
System.out.println(memoizedAdd2.apply(2));
System.out.println(memoizedAdd2.apply(4));
System.out.println(memoizedAdd2.apply(1));
}
}
nên in:
Thêm 2 đến: 1
Thêm 2 vào: 2
Thêm 2 đến: 3
Thêm 2 đến: 4
Bạn có thể thấy rằng 2 time memoizedAdd2 được gọi (áp dụng) cho các đối số 2 và 1, tính toán trong áp dụng không thực sự chạy, nó chỉ lấy các kết quả được lưu trữ.
Nguồn
2010-10-14 17:24:14
Làm cách nào để triển khai theo cách tổng quát với tư cách là người trang trí cho phương pháp của tôi? – Albert
@Albert: Như Benoit đã nói, không có việc triển khai bản địa này (nghĩa là bạn không thể làm điều này theo cách chung mà không cần hack Java), vì công cụ trang trí python sử dụng một số "siêu thông tin" về hàm. I E. có thể trong python để cho người trang trí thay đổi chức năng ban đầu. Đây là - theo như tôi biết - không thể trong Java. – phimuemue
"bạn có thể thực hiện nó một cách dễ dàng, như một trang trí của phương pháp của bạn." <- làm thế nào tôi có thể làm điều đó như một người trang trí? Hay ý bạn là gì? – Albert