我建议为 counter 和 result 单独的类:
class Counter {
private int value = 0;
public void inc() {
value++;
}
public int get() {
return value;
}
}
class Result {
public final long value;
public final int calls;
public Result(long value, int calls) {
super();
this.value = value;
this.calls = calls;
}
public final long getValue() {
return this.value;
}
public final int getCalls() {
return this.calls;
}
}
像这样使用
public class FibonacciWithCounter {
static Result fibonacci(long n) {
final Counter counter = new Counter();
final long value = fibonacci(n, counter);
return new Result(value, counter.get());
}
static long fibonacci(long n, Counter counter) {
counter.inc();
if (n == 0)
return n;
else if (n == 1)
return n;
else
return fibonacci(n - 1, counter) + fibonacci(n - 2, counter);
}
public static void main(String[] args) {
final Result result = fibonacci(14);
System.out.println("Result is " + result.value
+ " (" + result.getCalls() + " calls)");
}
}
所以没有静态,每个参数/类都清楚地描述了它的用途。我更喜欢这个,因为它更具表现力,即使这个版本是最长的版本(由于附加类的样板)。