开发者

I need a pattern for constructing trees of objects

I've got some code (C#) that builds a tree of polymorphic objects. Depending on the type, an object may have 0-7 children. Right now, the objects' constructors do nothing, and I construct the whole object tree using a recursive helper function:

// pseudocode
void BuildTree(Node root) {
    if(root is A) {
        root.a_data = ...
        root.开发者_如何学Ca_child = GenerateNewNode(some_constraints); 
        BuildTree(root.a_child)
    } else if(root is B) {
        // same stuff, for B.  Note B may have different chldren, etc
    }
}

This all seems really inelegant, so basically I'm looking for a pattern that can help me here. The BuildTree function seems to be a policy of some kind, and I'd like to be able to use different policies in the future.

Oh, another complicating factor. There are things in BuildTree which are conditional on earlier things BuildTree has done. For example, if I've ever generated a B, then I need to do XYZ to C nodes. Or if I'm currently generating children of an A, then don't generate a D.


Sounds like you need to stick a polymorphic method on each node, so that every node becomes capable of building itself.

public class Node
{
    public virtual BuildNode(IBuildStrategy strategy)
    {
    }
}

That way you can simply call

root.BuildNode(new InitialNodeBuildingStrategy());

to populate the tree while still allowing for custom strategies within subtrees.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜