使用 2 种可能方法之一的 Java 接口(interface)/回调

标签 java methods interface callback

我已经阅读了 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/

相关文章:

java - 定义API时应该返回CompletableFuture还是Future?

java - 用于 Spring-Data-JPA 注释的 setMaxResults?

java - 能够实例化接口(interface)

java - 依赖倒置和分离接口(interface)模式(或一般的接口(interface)代码)之间有什么区别?

java - 访问plsql函数时出错: invalid name pattern

java - 从文件名生成唯一的 IRI

c++ - C++ 中的成员与方法参数访问

pointers - 修改取消引用的结构指针会更改大多数结构值,但不会更改 slice

javascript - 我如何使用一个 "if"来完成相同的工作?

interface - typescript 0.9 接口(interface)导出。是否可以?