Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat advantage will Composite pattern bring me over just Array?
    text
    copied!<p>I'm recently working on a tree structure, multiple nodes, multiple and increasable levels, and a print() method. At first, i thought it should be a Composite, i then wrote down some possible design and codes:</p> <p><img src="https://farm3.static.flickr.com/2596/3807730874_4d6d5ed7ee_o_d.gif" alt="alt text"></p> <pre><code>$struc = new Node(‘name0’, ‘id0’, ‘desc0’); $node1 = new Node(‘node1’, ‘id1’, ‘desc1’); $node2 = new Node(‘node2’, ‘id2’, ‘desc2’); $node3 = new Node(‘node3’, ‘id3’, ‘desc3’); $leaf1 = new Leaf(‘leaf1’, ‘ld1’, ‘lesc1’); $leaf2 = new Leaf(‘leaf2’, ‘ld2’, ‘lesc2’); $leaf3 = new Leaf(‘leaf3’, ‘ld3’, ‘lesc3’); $leaf4 = new Leaf(‘leaf4’, ‘ld4’, ‘lesc4’); $struc.add($node1); $struc.add($node3); $node1.add($leaf1); $node1.add($leaf2); $node1.add($node2); $node2.add($leaf3); $node3.add($leaf4); </code></pre> <p>Looks good, i think and begin coding, print() method may follow Iterator pattern later. But during coding, i feel is it too complex for these simple nodes? And i have to instantiate a lot of concrete classes (more than 50+, and increasing). I then stopped and thinking a simple similar way by using array:</p> <pre><code>-- Structure Class -- //To be more readable and clear, array here could be //divided to 3 arrays(root/nodes/leafs), then connect //in a similar way Composite does. $struc = array('name0', 'id0', 'desc0', 'children'=&gt;array( array('node1', 'id1', 'desc1', 'children' =&gt; array( array('leaf1', 'ld1', 'lesc1'), array('leaf2', 'ld2', 'lesc2'), array('node2', 'id2', 'desc2', 'children'=&gt;array(array('leaf3', 'ld3', 'lesc3')) ) ) ), array('node3', 'id3', 'desc3', 'children' =&gt; array(array('leaf4', 'ld4', 'lesc4')) ) ) ); function print($node = $this-&gt;struct) { ... if(isset($node['children'])) $this-&gt;print($node['children']); ... } </code></pre> <p>The two designs look very similar, now i'm a little confused, what's the value of Composite pattern, am i missed something important of this pattern?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload