我在switch里面使用enums作为250多个case的替代。
switch(variable){
case "NAME":
case "MIDDLE":
case "LAST":
return a();
break;
case "SUFFIX":
case "PREFIX":
return b();
break;
}
我在使用enum处理上述情况时遇到了问题。
public enum Action {
NAME {
@Override
public String getVariableData() {
return a();
}
},LAST {
@Override
public String getVariableData() {
return a();
}
},MIDDLE {
@Override
public String getVariableData() {
return a();
}
},SUFFIX {
@Override
public String getVariableData() {
return b();
}
},PREFIX {
@Override
public String getVariableData() {
return b();
}
};
public abstract String getVariableData();
}
这里NAME,MIDDLE,LAST返回相同的值。但我的问题是,为什么我需要实现saperately和如何重用现有的实现。Please Help me to reduce the code my reusing the existing implementations.
我想,你可以创建一组接口和实现,就像策略模式一样。https:/www.baeldung.comjava-strategy-pattern:
interface Action {
String getVariableData();
}
interface ActionA extends Action {
default String getVariableData() {
return "a";
}
}
interface ActionB extends Action {
default String getVariableData() {
return "b";
}
}
enum ActionAImpl implements ActionA {
NAME, MIDDLE, LAST
}
enum ActionBImpl implements ActionB {
SUFFIX, PREFIX
}
public static String doAction(Action a) {
return a.getVariableData();
}
public static void main(String[] args) {
System.out.println(doAction(NAME));
System.out.println(doAction(SUFFIX));
}
或者可以用行动地图来完成,比如:
public static String process (ActionCode code){
return actions.get(code).getVariableData();
}
Map<ActionCode, Action> actions = new HashMap<>();
actions.put(ActionCode.NAME, DefaultActions::getDefaultVariableData1);
actions.put(ActionCode.MIDDLE, DefaultActions::getDefaultVariableData2);
actions.put(ActionCode.LAST, () -> "custom info");
enum ActionCode {
NAME, MIDDLE, LAST, ...
}
interface Action {
String getVariableData();
}
final class DefaultActions {
static String getDefaultVariableData1() {
return "a";
}
static String getDefaultVariableData2() {
return "b";
}
}