基本上,我编写了一个微分方程解算器类,它将从“方程”类中提取方程,并使用rK4方法求解它。
我遇到的主要问题是,如果不通过继承扩展并获得访问权限,或者在ODE类中创建公式方法的特定实例,我无法找到将方法发送到另一个类的方法。
例如,我如何让下面的代码工作?(请记住,我不允许在ODE类中创建公式方法的特定实例):
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.
}
}
发布于 2014-10-25 02:13:51
我将使用一个接口来封装二进制方法的概念,并允许回调,类似于:
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));
}
}
https://stackoverflow.com/questions/26558613
复制