如果您可以接受一级间接,那么我下面介绍的方法会将重复代码减少到最低限度。
首先,考虑以下供应商接口及其内部类:
public interface PropertiesSupplier {
Properties properties();
public static final class Properties {
private final int value1;
private final String value2;
private final double value3;
private Properties(int value1, String value2, double value3) {
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}
public static Properties of(int value1, String value2, double value3) {
return new Properties(value1, value2, value3);
}
public int getValue1() {
return this.value1;
}
public String getValue2() {
return this.value2;
}
public double getValue3() {
return this.value3;
}
@Override
public String toString() {
return "Properties [value1=" + this.value1 + ", value2=" + this.value2 + ", value3=" + this.value3
+ "]";
}
}
}
这里没什么神奇的。内部类只是一个 beanprivate final
字段、用于初始化它们的私有构造函数、公共 getter、工厂方法和重写toString()
方法。该接口仅定义一种返回内部类实例的方法。请注意,内部类是最终的。这个想法是强制不变性,这样它的属性就不允许改变。
然后,让我们创建几个将实现此接口的枚举。让我们从MyEnum1
,它定义了两个值:
public enum MyEnum1 implements PropertiesSupplier {
ENUM_1_CONST_1(Properties.of(1, "hello", 0.123)),
ENUM_1_CONST_2(Properties.of(2, "goodbye", 7.54));
private final Properties p;
private MyEnum1(Properties p) {
this.p = p;
}
@Override
public Properties properties() {
return this.p;
}
}
接下来是MyEnum2
,它只定义一个值:
public enum MyEnum2 implements PropertiesSupplier {
ENUM_2_CONST_1(Properties.of(9, "hey dude", 547.21578));
private final Properties p;
private MyEnum2(Properties p) {
this.p = p;
}
@Override
public Properties properties() {
return this.p;
}
}
如您所见,两个枚举都实现了PropertiesSupplier
接口,因此他们必须提供一个实现Properties properties()
方法。为了遵守这一点,他们必须封装一个实例Properties
,他们在构造函数中收到。
所以现在,在这种间接寻址之后,所有枚举中唯一重复的代码就是Properties
字段、接收它作为参数的构造函数及其 getter 方法。
这是一个显示如何使用枚举的示例:
MyEnum1 e1 = MyEnum1.ENUM_1_CONST_2;
MyEnum2 e2 = MyEnum2.ENUM_2_CONST_1;
System.out.println(e1.name() + " - " + e1.properties());
System.out.println(e2.name() + " - " + e2.properties());
此代码产生以下输出
ENUM_1_CONST_2 - Properties [value1=2, value2=goodbye, value3=7.54]
ENUM_2_CONST_1 - Properties [value1=9, value2=hey dude, value3=547.21578]