title: Anonymous or real class definition when using visitor pattern?
body: <p>When you use the Visitor pattern and you need to get a variable inside visitor method, how to you proceed ?</p>
  
  <p>I see two approaches. The first one uses anonymous class : </p>
  
  <pre><code>// need a wrapper to get the result (which is just a String)
  final StringBuild result = new StringBuilder();
  final String concat = "Hello ";
  
  myObject.accept(new MyVisitor() {
  
      @Override
      public void visit(ClassA o)
      {
          // this concatenation is expected here because I've simplified the example
          // normally, the concat var is a complex object (like hashtable) 
          // used to create the result variable 
          // (I know that concatenation using StringBuilder is ugly, but this is an example !)
          result.append(concat + "A");
      }
  
      @Override
      public void visit(ClassB o)
      {
          result.append(concat + "B");
      }
  });
  
  System.out.println(result.toString());
  </code></pre>
  
  <p>Pros &amp; Cons : </p>
  
  <ul>
  <li>Pros : you do not need to create a class file for this little behavior</li>
  <li>Cons : I don't like the "final" keyword in this case : the anonymous class is less readable because it calls external variables and you need to use a wrapper to get the requested value (because with the keyword final, you can't reassign the variable)</li>
  </ul>
  
  <p>Another way to do it is to do an external visitor class :</p>
  
  <pre><code>public class MyVisitor
  {
      private String result;
      private String concat;
  
      public MyVisitor(String concat)
      {
          this.concat = concat;
      }
  
      @Override
      public void visit(ClassA o)
      {
          result = concat + "A";
      }
  
      @Override
      public void visit(ClassB o)
      {
          result = concat + "B";
      }
  
      public String getResult()
      {
          return result;
      }
  }
  
  MyVisitor visitor = new MyVisitor("Hello ");
  myObject.accept(visitor);
  System.out.println(visitor.getResult());
  </code></pre>
  
  <p>Pros &amp; Cons : </p>
  
  <ul>
  <li>Pros : all variables are defined in a clean scope, you don't need a wrapper to encapsulate the requested variable</li>
  <li>Cons : need an external file, the getResult() method must be call after the accept method, this is quite ugly because you need to know the function call order to correctly use the visitor</li>
  </ul>
  
  <p>You, what's your approach in this case ? Preferred method ? another idea ?</p>