如何在enums中重用现有的实现?

问题描述 投票:0回答:1

我在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.

java enums switch-statement
1个回答
0
投票

我想,你可以创建一组接口和实现,就像策略模式一样。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";
    }
}  
© www.soinside.com 2019 - 2024. All rights reserved.