null pattern and composite pattern don't play nice together
In this composite tree I am keeping a reference to the parent node for flexible tree traversal. I don't want to have to check the parent for a null reference all the time but if I make a NullNode class and initialize each node's parent to this I get a stack overflow since the NullNode has a NullNode has a NullNode has a.... ad infinitum I've tried setting the NullNode's parent to null but then I st开发者_Python百科ill have to do a null reference check for the parent which seems to defeat the purpose. anyone run into this? What, if anything can be done?
thanks!
if I make a NullNode class and initialize each node's parent to this I get a stack overflow since the NullNode has a NullNode has a NullNode has a.... ad infinitum I've tried setting the NullNode's parent to null but then I still have to do a null reference check for the parent which seems to defeat the purpose. anyone run into this?
Your NullNode
doesn't need to actually contain another NullNode
as parent. Just implement getParent()
in NullNode
(or whatever you're calling it) to return this
or self
or whatever means that in your language.
However, this may still be a bad idea, as you do have to stop the traversal at some point. The above gets you past the constructor recursion, but there's no root for the tree as it's NullNodes all the way up or turtles all the way down or something like that.
This will all be much easier to talk about if you actually show the code even though it's not working, and describe your plans for usage a bit.
Counter example (extreme pseudo code):
class NullNode(): Component{
public NullNode(){
}
public something SearchUp(){
return null;
}
}
class Node: Component{
public Node(t){
this.parent = NullNode();
}
public void SetParent(Component parent){
this.parent = parent;
}
public something SearchUp(){
return self.parent.SearchUp();
}
}
abstract class Component{
Component parent
public Component(){
}
public something SearchUp();
}
精彩评论