java - 构建该对象的更好模式?

标签 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.BODY, 4, 9),
  new MetaTypeAttribute(AttributeType.AGILITY, 1, 6),
  new MetaTypeAttribute(AttributeType.REACTION, 1, 6)
 );

 MetaType(MetaTypeAttribute body, MetaTypeAttribute agility, MetaTypeAttribute reaction) {
 }
}

因此有一个 MetaType 枚举;每个 MetaType 指定一组固定的 MetaTypeAttributes,其中包含该属性的最小值和最大值。

我讨厌这种语法。它太长了,很难看,而且它并不能阻止我传递错误的 AttributeType(AttributeType 应与 MetaType 构造函数的参数顺序相匹配;AttributeType.BODY > body 等)。我想要的是一个更好的模式来确保使用这种精确的方案构造对象。

此代码是缩写的。实际上有 9 种 AttributeType。

有什么改进建议吗?

最佳答案

    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);}
}

关于java - 构建该对象的更好模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3641388/

相关文章:

EF Core 中的枚举列表

Java读取文件名并按升序存储

java - 如何在 Spring @Service 和非 Spring 对象之间集成?

java - 使用 GWT 应用程序 - 是否有解决方法可以使 IE8 正确处理/渲染长度超过 32k 的 Base64 图像 url?

c++ - 内存管理模式

java - java核心的Iterator违反单一职责原则

typescript - 联合类型枚举的参数?

java - 在antlr语法g4文件中使用Java代码

java - JavaMail 中的 props.put ("mail.smtp.host", host) 是做什么的?

java - 获取 SimpleDateFormat 的模式