简体   繁体   中英

Java Interfaces/Callbacks for Using 1 of 2 Possible Methods

I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.

EDIT : added my code

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

If you want to use interfaces something like this would work. I have a MathFunc interface that has a calc method. In the program I have a MathFunc for mutliplication and one for addition. With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.

public interface MathFunc {

   int calc(int a, int b);

}

and you can use it like that:

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
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM