Można użyć interfejsu Function w guava biblioteki Google, aby łatwo osiągnąć to, co jesteś po:
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));
}
}
powinien wydrukować:
dodanie 2 do: 1
Dodawanie 2 do: 2
Dodawanie 2 do: 3
dodanie 2 do: 4
Widać, że 2nd time memoizedAdd2 jest wywoływany (stosowany) do argumentów 2 i 1, the obliczenia w zastosowaniu nie są w rzeczywistości uruchomione, po prostu pobrano zapisane wyniki.
Jak mogę go zrealizować w ogólny sposób jako dekorator mojej metody? – Albert
@Albert: Jak Benoit stwierdził, nie ma natywnej implementacji tego (tj. Nie można tego zrobić w sposób ogólny bez hakowania w Javie), ponieważ rzeczownik dekoratora pythona używa pewnych "meta-informacji" dotyczących tej funkcji. To znaczy. w pytonie można pozwolić dekoratorowi zmienić pierwotną funkcję. Jest to - o ile mi wiadomo - niemożliwe w Javie. – phimuemue
"możesz go łatwo wdrożyć, jako dekorator twojej metody." <- jak mogę to zrobić jako dekorator? Albo co masz na myśli? – Albert