My code looks like below:
enum EnumType {
CATEGORY,
GROUP,
MAIN
}
Methods:
public void call(EnumType type){
switch(type):
case CATEGORY:
return methodForCategory();
case GROUP:
return methodForGroup();
...
}
public void methodForCategory(){
... Operations according to EnumType.CATEGORY
}
public void methodForGroup(){
... Operations according to EnumType.GROUP
}
public void methodForMain(){
... Operations according to EnumType.MAIN
}
But I want to call it without switch/case like below;
public void call(EnumType type){
methodForType(EnumType type);
}
Is it possible or is there any better alternative?
解决方案
You can create the method implementation inside the enum as below:
public enum EnumType {
CATEGORY {
@Override
public void processMethod() {
// Do something here
}
},
GROUP {
@Override
public void processMethod() {
// Do something here
}
},
MAIN {
@Override
public void processMethod() {
// Do something here
}
};
public abstract void processMethod();
}
And update call method implementation as:
public void call(EnumType type){
type.processMethod();
}
And switch code should not return anything as method return type is void.