2015-05-28 16 views
0

我已經閱讀了Java接口(回調),因爲我被教授告知我應該在我的程序中使用回調。在我的代碼中,我可以從中選擇兩個數學函數。當我想要改變函數時,我沒有做一個方法activate()和改變裏面的代碼(從一個函數到另一個函數),他說我應該使用回調函數。不過,從我讀過的關於回調的內容中,我不確定這將會如何。Java接口/回調使用2個可能的方法之一

編輯:加入我的代碼

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); 
    } 
} 
+0

你可以發表你的相關的代碼? –

+0

增加了一些代碼。 –

+0

該代碼不應該編譯,因爲你可能沒有在接口實現 – danielspaniol

回答

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 
    } 

} 
+0

謝謝!我很感激。 If語句否定了我認爲回調的有用性,但它仍然是很好的代碼。我最終做了一些非常相似的事情。然而,在我的程序方法中,我傳遞了一個對象類型和一個數字,並將該數字用作傳遞對象上方法的參數。 –

+0

這只是一個例子來說明如何使用接口來切換不同的功能^^ – danielspaniol