打开一个可扩展类。

huangapple 未分类评论45阅读模式
英文:

Switch on an extensible class

问题

在Java中,你可以针对枚举类型使用switch语句。假设你有类似以下定义的枚举类型:

enum Color { RED, ORANGE, YELLOW ... }

然后你可以这样使用:

switch (color) {
    case RED:
        ...

现在,我有一个特定的需求,需要在一类对象上使用switch语句,以示例为例,我们称之为"颜色",但也需要在运行时创建更多的颜色对象。但是使用枚举无法实现这一点。

当然,switch语句只能了解在编译时定义的枚举成员。这没关系。如果在运行时我创建了teal、maroon和aquamarine等颜色,我仍然只需要针对基本颜色如红色、绿色和蓝色来使用switch语句。但是我需要能够创建其他颜色对象。

如果枚举支持子类,那么子类会是一个很好的解决方案,比如class OtherColor extends Color ...,但是枚举无法作为子类或被子类化。

我可以放弃使用枚举,只需创建一个常规类,并添加一些静态实例... 但是switch语句在这些对象上将无法工作。

我所知的最接近的解决方案是使用class Color,结合switch (color.toString())。但这不是最优的解决方案,因为这意味着拼写错误无法在编译时捕获,而且在运行时必须花费额外的时钟周期进行字符串比较。(次佳解决方案是分配整数ID标签,但会影响代码的可维护性。)

是否有另一种解决方案呢?

英文:

In Java, you can switch on an enum. Say you have something like

enum Color { RED, ORANGE, YELLOW ... }

you can then

switch (color) {
case RED:
    ...

Now, I have a particular requirement for switching on a class of objects, call them colors for the sake of illustration, but also create more of them at runtime. And you cannot do that with enums.

Of course, the switch statement can only know about the ones that are defined at compile time. That's okay. If at runtime I create teal, maroon and aquamarine, I still only need to switch on the basic colors like red, green and blue. But I need to be able to create the other ones.

Subclasses would do fine, if I could create class OtherColor extends Color ... but enums cannot subclass or be subclassed.

I could forget about enums and just create a regular class with some static instances... but then switch will not work on those.

The closest solution I know of is class Color together with switch (color.toString()). This is suboptimal because it means typos are not caught at compile time, and extra clock cycles must be spent doing string comparisons at runtime. (Second-best solution would be to assign integer ID tags, which harms maintainability of the code.)

Is there another solution?

huangapple
  • 本文由 发表于 2020年4月6日 17:28:23
  • 转载请务必保留本文链接:https://java.coder-hub.com/61056679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定