避免枚举中出现长参数列表的最佳方法是什么?是否存在与构建器模式等效的枚举?我试图避免切换枚举值,因为这会违反 DRY 原则。
正如您在下面看到的,跟踪多个参数可能很困难:
public enum ExmapleEnum {
FOO(20, 75, 100),
BAR(41, 6, 240),
BAZ(2, 19, 80);
private int mAge;
private int mHeight;
private int mWeight;
private ExmapleEnum(int age, int height, int weight) {
mAge = age;
mHeight = height;
mWeight = weight;
}
// Remainder omitted...
}
最佳答案
你可以做
public enum ExampleEnum {
FOO(InitParams.builder()
.setAge(20)
.build()),
...
private ExampleEnum(InitParams params) {
...
}
private static class InitParams {
...
}
}
然后,您可以根据构建的 InitParams
填充字段,也可以将 InitParams
对象存储为字段。
关于java - 具有许多参数的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28033244/