如何通过抽象类实现函数指针的 Java 等效项

发布于 2024-10-18 15:25:39 字数 777 浏览 2 评论 0原文

我试图使用没有 switch case 或 if/else 语句的跳转表创建一个简单的 4 函数计算器。我知道我可以通过函数指针创建跳转表,但我有点茫然。我已经从程序的加法和减法部分开始,但正在尝试掌握要使用的设计/策略。将方法放入数组时我也遇到错误,到目前为止,这就是我所拥有的:

public class Calculator {

          public abstract class Functor{

            abstract double Compute(double op1, double op2);
            }

     class Addition extends Functor
    {

        public double Compute(double op1, double op2){ return op1 + op2;}
    }

    class Subtraction extends Functor
    {

        public double Compute(double op1, double op2){ return op1 - op2;}
    }



    public static void main(String[] args) {

        Functor add = new Addition();     // Problem here
        Functor sub = new Subtraction();  // and here



    }
}

非常感谢任何朝着正确方向迈出的帮助或想法! 提前致谢!

Im trying to to create a simple 4 function calculator using a jump table without switch case or if/else statements. I understand I can create the jump table via function pointers but I am kindda blanking out. I've started with the addition and subtraction part of the program but am trying to grasp the design/strategy to use. I am also getting an error when putting the method in the array, so far this is what i have:

public class Calculator {

          public abstract class Functor{

            abstract double Compute(double op1, double op2);
            }

     class Addition extends Functor
    {

        public double Compute(double op1, double op2){ return op1 + op2;}
    }

    class Subtraction extends Functor
    {

        public double Compute(double op1, double op2){ return op1 - op2;}
    }



    public static void main(String[] args) {

        Functor add = new Addition();     // Problem here
        Functor sub = new Subtraction();  // and here



    }
}

any help or ideas for the step in the right direction is greatly appreciated!
thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

简美 2024-10-25 15:25:39

让我们试试这个:

public enum Operation {
  PLUS("+") {
    double apply(double x, double y) { return x + y; }
  },
  MINUS("-") {
    double apply(double x, double y) { return x - y; }
  },
  TIMES("*") {
    double apply(double x, double y) { return x * y; }
  },
  DIVIDE("/") {
    double apply(double x, double y) { return x / y; }
  };
  private final String symbol;

  Operation(String symbol) {
    this.symbol = symbol; 
  }

  @Override public String toString() {
    return symbol; 
  }
  abstract double apply(double x, double y);
}

只有当您使用具有泛型和枚举的 Java 5 或更高版本时,这才有效。它的作用是为您提供一组静态操作。您可以通过输入 Operation.PLUSOperation.MINUS 等来访问它们。

要测试它,请尝试以下操作:

public static void main(String[] args) {
  double x = Double.parseDouble(args[0]);
  double y = Double.parseDouble(args[1]);

  for (Operation op : Operation.values())
    System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}

有关更多信息,请参阅Effective Java,第二版 约书亚·布洛赫。

值得指出的是,Java 没有“函数指针”的概念。相反,您只需编写一个接口并编写一个实现该接口的类。在运行时选择要使用的正确类;因此,这是一个“跳转表”,但它隐藏在面向对象编程的语义后面。这称为多态性

Let's try this instead:

public enum Operation {
  PLUS("+") {
    double apply(double x, double y) { return x + y; }
  },
  MINUS("-") {
    double apply(double x, double y) { return x - y; }
  },
  TIMES("*") {
    double apply(double x, double y) { return x * y; }
  },
  DIVIDE("/") {
    double apply(double x, double y) { return x / y; }
  };
  private final String symbol;

  Operation(String symbol) {
    this.symbol = symbol; 
  }

  @Override public String toString() {
    return symbol; 
  }
  abstract double apply(double x, double y);
}

This will only work if you're using Java 5 or later, which has generics and enums. What this does is it gives you a static set of operations. You access them by typing Operation.PLUS or Operation.MINUS, etc.

To test it try this:

public static void main(String[] args) {
  double x = Double.parseDouble(args[0]);
  double y = Double.parseDouble(args[1]);

  for (Operation op : Operation.values())
    System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}

For more information consult Effective Java, Second Edition by Joshua Bloch.

It's worth pointing out that Java has no notion of "function pointers". Rather you simple write an interface and write a class that implements that interface. The correct class to use is selected at runtime; hence, that is a "jump table" but it's hidden behind the semantics of object-oriented programming. This is known as polymorphism.

梦屿孤独相伴 2024-10-25 15:25:39

虽然这很不错(除了没有可以正常工作的构造函数之外),但我会使用匿名类来做不同的事情。

abstract class Functor {


    public abstract double compute(double a, double b);

    public static void main(String[] args) {
        Functor add = new Functor() {
            // defining it here is essentially how you do a function pointer
            public double compute(double a, double b) { return a + b; }
        };

        Functor subtract = new Functor() {
            public double compute(double a, double b) { return a - b; }
        };

        System.out.println(add.compute(1.0,2.0));
        System.out.println(subtract.compute(1.0,2.0));

    }

}

结果:

C:\Documents and Settings\glowcoder\My Documents>java Functor
3.0
-1.0

C:\Documents and Settings\glowcoder\My Documents>

While that's decent (aside from not having constructors that work right) I'd do it different, using anonymous classes.

abstract class Functor {


    public abstract double compute(double a, double b);

    public static void main(String[] args) {
        Functor add = new Functor() {
            // defining it here is essentially how you do a function pointer
            public double compute(double a, double b) { return a + b; }
        };

        Functor subtract = new Functor() {
            public double compute(double a, double b) { return a - b; }
        };

        System.out.println(add.compute(1.0,2.0));
        System.out.println(subtract.compute(1.0,2.0));

    }

}

Result:

C:\Documents and Settings\glowcoder\My Documents>java Functor
3.0
-1.0

C:\Documents and Settings\glowcoder\My Documents>
浮华 2024-10-25 15:25:39

您没有任何构造函数可以将任何参数传递给您的子类,我不明白您认为如何在没有任何参数的情况下设置 opt1opt2以这些作为参数的构造函数。目前这不是正确的 Java 代码。

You don't have any constructors to pass in any arguments to your sub-classes, I don't understand how you think opt1 and opt2 are going to be set without any constructors with those as parameters. This is not correct Java code right now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文