我发现使用组合模式时,有一件事可以用不同的方式解决:将父亲元素与另一个组合元素关联。
我的意思是,如果“子”元素应该知道“父”元素,可以通过以下两种方式之一实现:
我的意思是,如果“子”元素应该知道“父”元素,可以通过以下两种方式之一实现:
by putting the parent element to the constructor:
Composite (Composite parent) { parent.addChild(this); this.parent = parent; } public void addChild(Composite child) { children.add(child); }
by using the addChild method which internally assigns a reference of itself to the added child:
public void addChild(Composite child) { children.add(child); child.setParent(this); }
现在,我的问题是要使用哪种方法?哪一种更可靠、更灵活、更少出现错误?有没有人经历过这两种方法,并决定选择其中一种?