As we know that java enum class :
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?
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();
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With