使用枚举值来表示二进制运算符或函数 [英] Using enum values to represent binary operators or functions

查看:147
本文介绍了使用枚举值来表示二进制运算符或函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方法来使用Java枚举中的值来表示操作或功能。我的猜测是,由于这是Java,所以不会有一个很好的方式来做,但是无论如何,我的枚举看起来像这样:

I'm looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn't going to be a nice way to do it, but here goes anyway. My enum looks something like this:

public enum Operator {
    LT,
    LTEQ,
    EQEQ,
    GT,
    GTEQ,
    NEQ;

    ...
}

其中 LT 表示 <(小于), LTEQ 表示< = (小于或等于)等等 - 你会得到想法。现在我想实际使用这些枚举值来应用一个运算符。我知道我可以使用一大堆if语句,但这是丑的OO方式,例如:

where LT means < (less than), LTEQ means <= (less than or equal to), etc - you get the idea. Now I want to actually use these enum values to apply an operator. I know I could do this just using a whole bunch of if-statements, but that's the ugly, OO way, e.g.:

int a = ..., b = ...;
Operator foo = ...; // one of the enum values
if (foo == Operator.LT) {
    return a < b;
}
else if (foo == Operator.LTEQ) {
    return a <= b;
}
else if ... // etc

喜欢能够做的是剪出这个结构,并使用某种一流的功能甚至多态,但我不太确定如何。如下所示:

What I'd like to be able to do is cut out this structure and use some sort of first-class function or even polymorphism, but I'm not really sure how. Something like:

int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

甚至

int a = ..., b = ...;
Operator foo = ...;
return a foo.convertToOperator() b;

但是据我所见,我不认为有可能返回一个操作员功能(至少不使用某些第三方库)。任何建议?

But as far as I've seen, I don't think it's possible to return an operator or function (at least, not without using some 3rd-party library). Any suggestions?

推荐答案

不仅可以这样做,它被用作经常引用的有效Java,第二版Josh Bloch 我不想踩他的版权,会在线寻找类似的例子...

Not only is this possible, it's used as an example in the frequently referenced Effective Java, Second Edition by Josh Bloch. I don't want to step on his copyright, will look for a similar example online...

好的,我记得的代码是在我之前链接的网站上免费提供。点击下载本书中使用的代码示例,然后查看 effective2 / examples / Chapter6 / Item30 / Operation.java

Okay, the code I remembered is freely available at the website I linked earlier. Click "Download the code samples used in this book", then look at effective2/examples/Chapter6/Item30/Operation.java.

这篇关于使用枚举值来表示二进制运算符或函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆