Re: When and where to use Visitor Pattern?



Sam Hwang wrote:
Hello,
I am confused about Visiotr Pattern. Observe this example from
<snip>
Why make it so complicated? Can't we use this one instead?
class IntExp1 extends Expression
{
   int value;

   void visit()
   {
      System.out.println(value);
   }
}

class AddExp1 extends Expression
{
  Expression e1, e2;

  void visit()
  {
     e1.visit();
    System.out.print(" + ");
    e2.visit();
  }
}
I dont know in what cirumstances the pattern is used sensablely. I hope
someone can address my confusion. Thanks!

Okay, suppose you instead wanted to find - the largest integer in your expression. - The smallest integer - count the number of additions - count the number of integers - find the leftmost integer - find the rightmost integer - write to a file, not System.out

You can either write a "visit" method for each of those tasks in the above list, thereby inserting lots of junk into your IntExp and AddExp classes, or you can use a visitor. Visitor moves methods into classes, which can structure the problem better.

--
Fast object persistence in C++  http://lightwave2.com/persist
A fast malloc/new replacement   http://lightwave2.com
Home                            http://visula.org/calum
.



Relevant Pages