简体   繁体   English

可选属性的类层次结构设计

[英]Class Hierarchy design for optional attribute

At the moment my application has the following class hierarchy: 目前,我的应用程序具有以下类层次结构:

  • "Class A" is the parent class “A类”是父类
  • "Class B" is the child class of "Class A" “B级”是“A级”的儿童班
  • "Class C" is the child class of "Class A" “C级”是“A级”的儿童班

At the moment, "Class A" has an attribute called "Attribute D" which is mandatory for "Class B" but optional in "Class C". 目前,“A类”具有称为“属性D”的属性,对于“B类”是强制性的,但在“C类”中是可选的。

May I know the best way to represent this data structure? 我可以知道表示此数据结构的最佳方法吗? such that rather than letting others referencing ClassA.getAttributeD without checking if it is NULL, we force them to use Class B and Class C to reference the field 这样,我们强制他们使用Class B和Class C引用该字段,而不是让其他人引用ClassA.getAttributeD而不检查它是否为NULL。

Add a constructor in Class B with Attribute D . 使用Attribute DClass B添加构造函数。 In Class C there is just a setter for this attribute. Class C ,只有这个属性的setter。

abstract class A {
   Object attributeD;

   void setAttributeD(Object attributeD) { this.attributeD = attributeD; }
   Object getAttributeD() { return attributeD; }
}

class B extends A {
   B(Object attributeD) { this.attributeD = attributeD; }
}

class C extends A {
}

Don't overuse inheritance. 不要过度使用继承。 Often it makes things more complicated as necessary. 通常它会使事情变得更加复杂。 You can see this already in your question. 您可以在问题中看到这一点。

Take a look at this: 看看这个:

Class A {
    private int d = 1;

    protected int getD() {
        return d;
    }
}

Class B extends A {
    public void doStuff() {
        B b = new B();
        System.out.println(b.getD());  
    }
}

Class C extends A {
    public void doStuff() {
        C c = new C();
        System.out.println(c.getD());  
    }
}

Your main problem is to avoid users accessing attribute D . 您的主要问题是避免用户访问attribute D You can do so by setting attribute D to be private, then declare protected methods to access the attribute. 您可以通过将attribute D设置为私有来执行此操作,然后声明受保护的方法以访问该属性。 This way, the subclasses will be able to access the attribute. 这样,子类就能够访问该属性。

Make the field in A protected, or keep it private and make its accessor protected. 使A中的字段受到保护,或将其保密,并使其访问者受到保护。

Thus, users of the class A cannot access the field, but class B and C can use it, and can make accessors public for it. 因此,A类用户无法访问该字段,但B类和C类可以使用它,并且可以为其公开访问者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM