How to reuse code in multiple Enum

As you know, the java enum class:

  • implicitly extends java.lang.Enum;
  • cannot extend to other enum classes.

I have several enum classes as shown below:

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

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

The method is aMethod()in listing ResourceStateand ServiceStateexactly the same.

OOP, if ResourceStateand ServiceStateare not enumerated, they need to abstract one and the same method of super-abstract class, for example:

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

but ResourceState cannot extend from AbstractState, do you have any ideas for work?

+5
source share
3 answers

, . , , -, , .

, , - , aMethod.

+3

Enums , . , - , , , :

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();
    }
}
+4

Safe Enum:

public class ResourceState {
    private ResourceState() {
    }

    public void aMethod() { .... }

    public static ResourceState RUNNING = new ResourceState();
    public static ResourceState STOPPING = new ResourceState();
    ....
}

aMethod, .

+2

All Articles