我已经阅读了 Java 接口(interface)(回调),因为一位教授告诉我应该在我的一个程序中使用回调。在我的代码中,有两个我可以从中“选择”的数学函数。当我想要更改函数时,他说我应该使用回调,而不是创建一个方法 activate() 并更改内部代码(从一个函数到另一个函数)。然而,根据我读到的有关回调的内容,我不确定这有什么用处。
编辑:添加了我的代码
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
最佳答案
如果你想使用这样的接口(interface)就可以了。
我有一个 MathFunc
接口(interface),它有一个 calc
方法。
在程序中,我有一个用于乘法的 MathFunc 和一个用于加法的 MathFunc。
使用 chooseFunc
方法,您可以选择两者之一,而使用 doCalc
,当前选择的 MathFunc
将执行计算。
public interface MathFunc {
int calc(int a, int b);
}
你可以这样使用它:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}
关于使用 2 种可能方法之一的 Java 接口(interface)/回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510147/