【问题标题】:Java Interfaces/Callbacks for Using 1 of 2 Possible Methods使用 2 种可能方法中的 1 种的 Java 接口/回调
【发布时间】:2015-05-28 14:57:35
【问题描述】:

我已经阅读了 Java 接口(回调),因为一位教授告诉我应该在我的一个程序中使用回调。在我的代码中,我可以从中“挑选”两个数学函数。当我想更改函数时,不要创建方法 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);
    }
}

【问题讨论】:

  • 能贴出你的相关代码吗?
  • 该代码不应编译,因为您可能在接口中没有实现
  • 对,我不是想编译上面的代码,而是展示一个我在做什么的例子

标签: java methods interface callback


【解决方案1】:

如果您想使用这样的接口,则可以使用。 我有一个MathFunc 接口,它有一个calc 方法。 在程序中,我有一个 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
   }

}

【讨论】:

  • 谢谢!我很感激。 If 语句否定了我认为回调的用处,但它仍然是很好的代码。我最终做了一些非常相似的事情。但是,在我的程序方法中,我传递了一个对象类型和一个数字,并且只是将数字用作传递对象的方法的参数。
  • 这只是一个示例,展示了如何使用接口在不同功能之间切换^^
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
相关资源
最近更新 更多