Java 该对象的构造更好的模式?
我正在构造具有如下数据结构的枚举值:Java 该对象的构造更好的模式?,java,design-patterns,enums,constructor,Java,Design Patterns,Enums,Constructor,我正在构造具有如下数据结构的枚举值: enum MetaType { HUMAN( new MetaTypeAttribute(AttributeType.BODY, 1, 6), new MetaTypeAttribute(AttributeType.AGILITY, 1, 6), new MetaTypeAttribute(AttributeType.REACTION, 1, 6) ), ORK( new MetaTypeAttribute(AttributeType.
enum MetaType {
HUMAN(
new MetaTypeAttribute(AttributeType.BODY, 1, 6),
new MetaTypeAttribute(AttributeType.AGILITY, 1, 6),
new MetaTypeAttribute(AttributeType.REACTION, 1, 6)
),
ORK(
new MetaTypeAttribute(AttributeType.BODY, 4, 9),
new MetaTypeAttribute(AttributeType.AGILITY, 1, 6),
new MetaTypeAttribute(AttributeType.REACTION, 1, 6)
);
MetaType(MetaTypeAttribute body, MetaTypeAttribute agility, MetaTypeAttribute reaction) {
}
}
所以有一个元类型的枚举;每个元类型指定一组固定的元类型属性,其中包括该属性的最小值和最大值
我讨厌这种语法。它太长,很难看,并且它不能阻止我传递错误的AttributeType(AttributeType应该与元类型构造函数的参数顺序匹配;AttributeType.BODY>BODY,等等)。我想要的是一个更好的模式,以确保对象是用这个精确的方案构造的
这个代码是缩写的。实际上有9个属性类型
<>是否有任何改进建议? 如果你考虑不同的属性类型,也许你应该真正创建那些属性类型作为类/子类而不是枚举。您将拥有OOP的所有优点来处理每种类型的行为(继承方法、方法重写等等),并且它们将是类型安全的
abstract class AbstractTypeAttribute{
private final int min, max;
public AbstractTypeAttribute(int min, int max){
//...
}
//...
}
class Body extends AbstractTypeAttribute{
public Body(int min, int max){
super(min, max);
//...
}
//...
}
您应该考虑这样做,而不是元属性和元类型。您也可以使用枚举继承和覆盖方法。和枚举是完全类型安全的。我看不出这有什么好处。顺便说一句,您的方法不提供常量。您不能继承枚举,它们实际上是最终的。枚举是类型安全的,但不是枚举内容,它不能用作类型。我不知道你在说什么常数。谢谢!我最终使用了这种模式。严格地说,当我这样做时,我不需要MetaTypeAttribute对象;我只是存储一个从构造函数参数填充的映射。
enum MetaType {
HUMAN(new MyRange(1,1), new MyRange(1, 10), new MyRange(1,10)
),
ORK(new MyRange(1,1), new MyRange(1, 10), new MyRange(1,10)
);
MetaType(MyRange body, MyRange agility, MyRange reaction) {
this.bodyAttrib = new MetaTaypAttibute(AttributeType.BODY, body);
this.agilityAttrib = new MetaTaypAttibute(AttributeType.AGILITY, agility);
this.reactionAttrib = new MetaTaypAttibute(AttributeType.REACTION, reactiony);}
}