I need a pattern for constructing trees of objects -
i've got code (c#) builds tree of polymorphic objects. depending on type, object may have 0-7 children. right now, objects' constructors nothing, , construct whole object tree using recursive helper function:
// pseudocode void buildtree(node root) { if(root a) { root.a_data = ... root.a_child = generatenewnode(some_constraints); buildtree(root.a_child) } else if(root b) { // same stuff, b. note b may have different chldren, etc } }
this seems inelegant, i'm looking pattern can me here. buildtree function seems policy of kind, , i'd able use different policies in future.
oh, complicating factor. there things in buildtree conditional on earlier things buildtree has done. example, if i've ever generated b, need xyz c nodes. or if i'm generating children of a, don't generate d.
sounds need stick polymorphic method on each node, every node becomes capable of building itself.
public class node { public virtual buildnode(ibuildstrategy strategy) { } }
that way can call
root.buildnode(new initialnodebuildingstrategy());
to populate tree while still allowing custom strategies within subtrees.
Comments
Post a Comment