我正在使用一些代码,在子代的构造函数中将子节点添加到它的父节点.代码看起来像这样:
类:
class Node1 {
public Node1(Node1 parent, String name) {
if(parent != null) {
parent.add(this);
}
this.parent = parent;
}
private void add(Node1 child) {
children.add(child);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Node1 parent = new Node1(null, "parent");
Node1 child1 = new Node1(parent, "child1");
Node1 child2 = new Node1(parent, "child2");
Run Code Online (Sandbox Code Playgroud)
通过这种方式实现它,类的用户Node1不必显式地将子节点(较少的代码)添加到它的父节点,并且您已经保证子节点具有父节点.
我个人不会这样写,但更像是以下内容:
class Node2 {
public Node2(String name) {
}
public void add(Node2 child) {
children.add(child);
child.setParent(this);
}
}
Node2 parent = new Node2("parent");
Node2 child1 = new Node2("child1");
parent.add(child1);
Node2 child2 = new Node2("child2");
parent.add(child2);
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如类所示实现它是一个好主意Node1还是有任何异议这样做?或者,为什么一个比另一个好?