In the topic called duplicate calculation in recursion, the author mention the exercise proposal below. I don't quite understand what would a more general and non-intrusive way of applying memoization looks like. Also how to apply design pattern called "decorator".
As an exercise, you could try to make memoization more general and non-intrusive, i.e. applying memoization without changing the original function. (Hint: one can refer to a design pattern called decorator).
The orginal solution which lack of generalization and non-intrusive was given as below :
import java.util.HashMap;
public class Main {
HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
private int fib(int N) {
if (cache.containsKey(N)) {
return cache.get(N);
}
int result;
if (N < 2) {
result = N;
} else {
result = fib(N-1) + fib(N-2);
}
// keep the result in cache.
cache.put(N, result);
return result;
}
}