Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As far as I can see the problem here is that you are defining how the tree will be traversed in the tree itself and not in the visitor. While this can be a valid approach (design patterns do have variations) I think that in this case is better to decouple the tree structure from the traversing order (pre-order, in-order, post-order). As a matter of fact a typical exercise when teaching this pattern is to write the three visitors, each one performing a different traversal.</p> <p>In your case I would:</p> <ol> <li><p>Represent the expressions as a tree just like you did, but removing form the accept the traversing parts. In your code the accept would look like:</p> <pre><code>public void accept(Visitor visitor) { visitor.visit(this); } </code></pre></li> <li><p>Define public getters for the childs of your nodes, so that the visitor can access them (<code>getChildA()</code>, <code>getChildB()</code> and <code>getValue()</code>).</p></li> <li><p>Write a visitor for the type of traversal that you need. For evaluating the expression you will generally use a post-order while for printing the expression you can use in-order (as in your example). So, for evaluating the expression you will end with something that looks like this:</p> <pre><code>class EvalVisitor implements Visitor{ public Integer visit(IntegerNode node) { return node.getValue(); } public Integer visit(PlusTreeExpression tree) { return this.visit(tree.getChildA()) + this.visit(tree.getChildB()); } public Integer visit(MultiplyTreeExpression tree) { return this.visit(tree.getChildA()) * this.visit(tree.getChildB()); } } </code></pre></li> </ol> <p>HTH</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