I want to reference the enum method to retrieve an algorithm class so that I can lazily load a new instance of the algorithm for use in the strategy design template.
In this example, I use enumeration to refer to three different classes of strategies that calculate the Fibonacci numbers: RecursiveFibonacciGenerator, IterativeFibonacciGeneratorand MemoizedFibonacciGenerator(all of which are inherited from FibonacciGenerator).
The code (with lines generating errors commented out with intent) is as follows:
package com.example.strategy;
public class Fibonacci {
private enum Algorithm {
RECURSIVE (RecursiveFibonacciGenerator.class),
ITERATIVE (IterativeFibonacciGenerator.class),
MEMOIZED (MemoizedFibonacciGenerator.class);
private final Class<T> algorithmClass;
private final T instance;
private <T extends FibonacciGenerator> Algorithm(Class<T> algorithmClass) {
this.algorithmClass = algorithmClass;
}
public T getInstance() {
if (this.instance == null) {
this.instance = this.algorithmClass.newInstance();
}
return this.instance;
}
}
public Integer getTerm(Integer termNumber) {
profileGenerator(termNumber, Algorithm.RECURSIVE);
profileGenerator(termNumber, Algorithm.ITERATIVE);
return profileGenerator(termNumber, Algorithm.MEMOIZED);
}
private Integer profileGenerator(Integer termNumber, Algorithm algorithm) {
System.out.print("Computing term using " + algorithm.toString() + " algorithm... ");
Long startTimeMilliseconds = System.currentTimeMillis();
Integer term = algorithm.getInstance().generateTerm(termNumber);
Long endTimeMilliseconds = System.currentTimeMillis();
Long computationTimeMilliseconds = endTimeMilliseconds - startTimeMilliseconds;
System.out.println("term computed in " + computationTimeMilliseconds + " milliseconds");
}
}
I would like to know how I can use this constructor enumto store a member variable of a type Class<T>.
Edit: Added full code to clarify intent
source
share