没有100%的surefire方法可以保持完整性。
通常采用的方法是使用一种方法来构建关系,并使用相同的方法来构建另一方向。但是,正如您所说,这并不能阻止任何人弄乱它。
下一步将是使某些方法可打包访问,以便至少与您的代码无关的代码不会破坏它:
class Parent { private Collection<Child> children; //note the default accessibility modifiers void addChild(Child) { children.add(child); } void removeChild(Child) { children.remove(child); }}class Child { private Parent parent; public void setParent(Parent parent){ if (this.parent != null) this.parent.removeChild(this); this.parent = parent; this.parent.addChild(this); }}实际上,您不会经常在课堂上为这种关系建模。取而代之的是,您将在某种存储库中查找所有子代的父母。



