将方法传递给另一个类的另一个方法

时间:2014-10-25 01:52:58

标签: java

基本上编码微分方程求解器类,它将从“方程”类中取出方程式并使用rK4方法求解它。

我遇到的主要问题是,我无法找到一种方法将方法发送到另一个类而不通过继承扩展和获取,或者在我的ODE类中创建该方程式的specefic实例。

例如,我如何使下面的代码工作? (记住我不允许在ODE类中创建Equation方法的特定实例):

public class Equations {
  public double pressureDrp( double a, double b) {
   return a+b;  //this is just a dummy equation for the sake of the question
  }
  public double waffles( double a, double b) {
   return a-b;  //this is just a dummy equation for the sake of the question
  }

}

public class ODE {
  //x being a method being passed in of "Equations" type.
  public double rK4( Equation method x ) {
    return x(3, 4);   
     //this would return a value of 7 from the pressureDrp method in class Pressure
    //if I had passed in the waffles method instead I would of gotten a value of -1.
  }
}

1 个答案:

答案 0 :(得分:0)

我会使用一个接口来封装二进制方法的概念并允许回调,例如:

interface BinaryEquation {
   double operate(double d1, double d2);
}

然后可以将它放在方程式类中,如下所示:

class Equations {
   public static class PressureDrop implements BinaryEquation {

      @Override
      public double operate(double d1, double d2) {
         return d1 + d2;
      }

   }

   public static class Waffles implements BinaryEquation {

      @Override
      public double operate(double d1, double d2) {
         return d1 - d2;
      }

   } 
}

如此使用:

class ODE {
   public double rk4(BinaryEquation eq) {
      return eq.operate(3, 4);   
   }
}

或者更好:

public class BinaryTest {
   public static void main(String[] args) {
      System.out.println("PressureDrop(3, 4): " + new Equations.PressureDrop().operate(3, 4));
      System.out.println("PressureDrop(3, 4): " + new Equations.Waffles().operate(3, 4));
   }
}