代码之家  ›  专栏  ›  技术社区  ›  RMorrisey

这个物体构造的更好模式?

  •  0
  • RMorrisey  · 技术社区  · 15 年前

    我正在构造具有如下数据结构的枚举值:

    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应该与元类型构造函数的参数顺序匹配;属性类型正文>车身等)。我想要的是一个更好的模式来确保一个对象是用这个精确的方案构造的。

    此代码为缩写。实际上有9个属性类型。

    有改进的建议吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   mhshams    15 年前
        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);}
    }
    
        2
  •  0
  •   Colin Hebert    15 年前

    如果您考虑不同的属性类型,也许您真的应该将这些属性类型创建为类/子类,而不是枚举。您将拥有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);
            //...
        }
        //...
    }
    

    您应该考虑这样做,而不是元属性和元类型太。