猿问

如何在没有实现的情况下删除类之间的重复代码?

我编写了许多函数的实现来计算给定位置的斐波那契数。


Fibonacci Class:这个类帮助我测试每个实现而无需重写相同的测试代码。我不想在fibonacci(n - 2).add(fibonacci(n - 1));这里添加“ ”,因为有些实现不使用它(命令式迭代、功能迭代)。


public interface Fibonacci {

  BigInteger fibonacci(int n);


}

递归斐波那契类


public class SimpleRecursiveFibonacci implements Fibonacci{


  public BigInteger fibonacci(int n) {

    if(n < 2) {

      return BigInteger.ONE;             

    }


    return fibonacci(n - 2).add(fibonacci(n - 1));

  }

}

和 MemorizedRecursiveFibonacci 类


public class MemoizedRecursiveFibonacci implements Fibonacci{

  private Map<Integer, BigInteger> cache = new HashMap<>();


  public BigInteger fibonacci(int n) {

    if(n < 2) {

      return BigInteger.ONE;

    }

    if(!cache.containsKey(n)){

      BigInteger currentFibonacci = fibonacci(n - 2).add(fibonacci(n - 1));

      cache.put(n, currentFibonacci);

    }


    return cache.get(n);

  }

}

如我所见,MemorizedRecursiveFibonacci 类中有一些重复的代码


 if(n < 2) {

      return BigInteger.ONE;


  BigInteger currentFibonacci = fibonacci(n - 2).add(fibonacci(n - 1));

我怎样才能保持干燥?删除重复的代码?


白衣非少年
浏览 144回答 2
2回答

慕后森

该MemorizedRecursiveFibonacci可以委托给一个RecursiveFibonacci实例:public class MemoizedRecursiveFibonacci implements Fibonacci {&nbsp; SimpleRecursiveFibonacci simple = new SimpleRecursiveFibonacci();&nbsp; private Map<Integer, BigInteger> cache = new HashMap<>();&nbsp; public BigInteger fibonacci(int n) {&nbsp; &nbsp; if(!cache.containsKey(n)) {&nbsp; &nbsp; &nbsp; BigInteger currentFibonacci = simple.fibonacci(n);&nbsp; &nbsp; &nbsp; cache.put(n, currentFibonacci);&nbsp; &nbsp; }&nbsp; &nbsp; return cache.get(n);&nbsp; }}或者,更优雅地,使用 Java 8 Map#computeIfAbsent:public class MemoizedRecursiveFibonacci implements Fibonacci {&nbsp; SimpleRecursiveFibonacci simple = new SimpleRecursiveFibonacci();&nbsp; private Map<Integer, BigInteger> cache = new HashMap<>();&nbsp; public BigInteger fibonacci(int n) {&nbsp; &nbsp; return cache.computeIfAbsent(n, k -> simple.fibonacci(k));}

白板的微信

那么抽象的公共父级呢?像这样的东西:public abstract class ParentFibonacci implements Fibonacci {&nbsp; &nbsp; protected BigInteger getFirstValues(int n) {&nbsp; &nbsp; &nbsp; &nbsp; if (n < 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return BigInteger.ONE;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return BigInteger.ZERO;&nbsp; &nbsp; }}这样你的斐波那契实现需要实现 Fibonacci.fibonacci(int n) 并且可以使用父方法。public class SimpleRecursiveFibonacci extends ParentFibonacci {&nbsp; &nbsp; public BigInteger fibonacci(int n) {&nbsp; &nbsp; &nbsp; &nbsp; if (n < 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return getFirstValues();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return fibonacci(n - 2).add(fibonacci(n - 1));&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答