Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code in multiple Enum

Tags:

java

oop

enums

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?

like image 292
BlackJoker Avatar asked Mar 20 '13 12:03

BlackJoker


2 Answers

Enums cannot extend other classes, but can implement interfaces. So, a more object oriented approach would be to make your enums implement a common interface and then use delegation to a support class that provides the real implemetation:

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();
    }
}
like image 157
dcernahoschi Avatar answered Sep 24 '22 03:09

dcernahoschi


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.

like image 39
Marko Topolnik Avatar answered Sep 23 '22 03:09

Marko Topolnik