Java Enum 或其他集合

标签 java enums

我们目前有两个客户代码“CUSTA”和“CUSTB”。 CUSTA 可以执行操作 A1、A2、A3、A4、A5、A6。 CUSTB 可以根据某些条件执行操作 B1、B2、B3、B4、B5、B6。目前他们不希望有任何更多的客户代码,但我希望设计灵活。这些可以存储在数据库中,但正如我提到的,因为很长一段时间内不太可能有另一个客户代码,所以需要用代码表示。

应用逻辑基本算法长这样

if ConditionX is true
then if customerCode is "CUSTA"
     then  applicableOperation = 'A1'
     else
         if customerCode is "CUSTB"
         then applicableOperation = 'B1'
      end
else
     if ConditionY is true     
     then
         if customerCode is "CUSTA"
         then  applicableOperation = 'A2'
         else
             if customerCode is "CUSTB"
              then applicableOperation = 'B2'
          end
      else

...................... .....................

我可以编写 switch 语句等来清理算法,但我主要关心的是如何表示“CUSTA”、“CUSTB”、“A1”、“A2”、“A3”、“A4”... “A6”、“B1”、“B2”……“B6”。客户代码是否像

public enum CustomerCode { CUSTA, CUSTB }
public enum OperationsForA{ A1, A2, A3,...A6 }
public enum OperationsForB{ B1, B2, B3...B6}

我应该创建一个 Map 吗,其中键是 CustomerCode 并将相应的操作添加为值。

解决此问题的最佳解决方案是什么。也应该灵活地添加 "CUSTC",例如,在未来。

谢谢

最佳答案

如果A1对应B1,A2对应B2,依此类推,则需要polymorphism .

这意味着您将拥有一个通用的 CustomerOperations界面。每个客户代码都会创建一个具体的实现 CustomerOperations接口(interface)并返回对应于Condition X的正确操作, Condition Y

设置您的界面:

interface CustomerOperations {
  Operation operationForX();
  Operation operationForY();
}

interface Operation {
  Result someMethod();
}

设置枚举并实现接口(interface):

enum OperationsForA implements Operation {
  A1, A2, A3;
  // Implement someMethod
}

enum OperationsForB implements Operation {
  B1, B2, B3;
  // Implement someMethod
}

enum CustomerCode implements CustomerOperations {
  CUSTA {
    Operation operationForX() {
      return OperationsForA.A1;
    }
    Operation operationForY() {
      return OperationsForA.A2;
    }
  },

  CUSTB  {
    Operation operationForX() {
      return OperationsForB.B1;
    }
    Operation operationForY() {
      return OperationsForB.B2;
    }
  }
  ;
}

示例用法:(这是多态性发生的地方)

public class Main {
  public static void main(String... args) {
    CustomerOperations operator = CustomerOperations.CUSTA;

    if (conditionX) {
      // Could be inlined, but I've separated it for type readability:

      // Get the appropriate operation from the operator.
      Operation thingToDoForX = operator.operationForX();

      // Run the operation and get the result
      Result result = thingToDoForX.someMethod();
    }
  }
}

关于Java Enum 或其他集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19105615/

相关文章:

entity-framework - Entity Framework 5 的新迁移功能是否完全支持枚举更改?

c++ - 使用编译时常量枚举转换为字符串

R 与 match.arg 类似的枚举参数 : How to choose a non-first element as default value?

java - Travis 部署一个 zip 而不是一个 jar

swift - 不确定在 swift 中使用什么数据类型

java - 如何将枚举序数转换为字符串?

java - Android 应用程序的 Eclipse 中的语法错误

java - 将电子邮件附件的链接保存在javamail下载的android数据库中

java - 字符二维

java - 这是有效的 Java 代码吗?我的老师声称是,但我真的不太确定