如何在多个枚举中重用代码 [英] How to reuse code in multiple Enum
问题描述
我们知道java enum类:
- 隐式扩展java.lang.Enum;
- 不能从任何其他枚举类扩展。
我有多个枚举类,如下所示:
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 :
- implicitly extends java.lang.Enum;
- 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屋!