如何在多个枚举中重用代码

Bla*_*ker 6 java oop enums

我们知道java enum类:

  1. 隐式扩展java.lang.Enum;
  2. 不能从任何其他枚举类扩展.

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

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

enum ServiceState {
    RUNNING, STOPPING,STARTTING,ERROR;//...
    void aMethod() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

该方法aMethod()在枚举ResourceStateServiceState是完全一样的.

在OOP中,如果ResourceStateServiceState不是枚举,他们应该将相同的方法抽象为超级抽象类,如下所示:

abstract class AbstractState{
    void aMethod() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

dce*_*chi 5

枚举不能扩展其他类,但可以实现接口.因此,更面向对象的方法是使您的枚举实现一个公共接口,然后使用委托给提供真正实现的支持类:

public interface SomeInterface {
    void aMethod();
}

public class SomeInterfaceSupport implements SomeInterface {
    public void aMethod() {
      //implementation
    }
}

public enum ResourceState implements SomeInterface {
    RUNNING, STOPPING,STARTTING;

    SomeInterfaceSupport someInterfaceSupport;

    ResourceState() {
        someInterfaceSupport = new SomeInterfaceSupport();
    }

    @Override
    public void aMethod() {
        someInterfaceSupport.aMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*nik 3

啊,是的,这个限制已经困扰了我好几次了。基本上,只要你有任何东西,除了应用枚举的最简单的模型,它就会发生。

我发现解决这个问题的最佳方法是一个实用程序类,其中包含从您的aMethod.