如何在多个枚举中重用代码 [英] How to reuse code in multiple Enum

查看:182
本文介绍了如何在多个枚举中重用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道java enum类:


  1. 隐式扩展java.lang.Enum;

  2. 不能从任何其他枚举类扩展。

我有多个枚举类,如下所示:

  enum ResourceState {
RUNNING,STOPPING,STARTTING; // ...
void aMethod(){
/ / ...
}
}

enum ServiceState {
RUNNING,STOPPING,STARTTING,ERROR; // ...
void aMethod() {
// ... ...
}
}

enum ResourceState ServiceState 中的方法 aMethod()如果 ResourceState ServiceState

>不是枚举,他们应该将相同的方法抽象为超抽象类,如下所示:

  abstract class AbstractState {
void aMethod(){
// ...
}
}

但是ResourceState无法从AbstractState扩展,你有什么想法可以解决吗?

解决方案

啊,是的,这个限制让我咬了几次。基本上,除了你应用枚举的最简单的模型之外,它会发生。



我发现解决这个问题的最好方法是使用静态的实用程序类从 aMethod 调用的方法。


As we know that java enum class :

  1. implicitly extends java.lang.Enum;
  2. can't extends from any other enum classes.

I have multiple enum class,like below:

enum ResourceState {
    RUNNING, STOPPING,STARTTING;//...
    void aMethod() {
        // ...
    }
}

enum ServiceState {
    RUNNING, STOPPING,STARTTING,ERROR;//...
    void aMethod() {
        // ...
    }
}

the method aMethod() in enum ResourceState and ServiceState is exactly the same.

in OOP,if ResourceState and ServiceState are not enum,they should abstract the same method to an super Abstract class,like this:

abstract class AbstractState{
    void aMethod() {
        // ...
    }
}

but ResourceState is unable to extends from AbstractState,Do you have any idea to work around?

解决方案

Ah yes, this limitation has bitten me a couple of times. Basically, it happens whenever you have anything but the most trivial model on which you apply the enum.

The best way I found to work around this was a utility class with static methods that are called from your aMethod.

这篇关于如何在多个枚举中重用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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