我们目前有两个客户代码“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/