Re: When and where to use Visitor Pattern?



On 22 Apr 2005 09:42:20 -0700, "Sam Hwang" <samhng@xxxxxxxxx> wrote:

One uses the visitor pattern when the method you would normally put in
the "expression" class does not belong there. For example, what if
you don't want "Expression" to know anything about System.out? Or,
what if there are many different ways to print an expression? In both
cases you don't want the printing code placed in the Expression
hierarchy, you want it decoupled from the expression hierarchy. the
Visitor pattern allows exactly that.

For more on this see:

http://www.objectmentor.com/resources/articles/visitor


>Hello,
>I am confused about Visiotr Pattern. Observe this example from
>nice.sf.net:
>
>package syntax;
>
>abstract class ExpressionVisitor
>{
> abstract void visitIntExp(IntExp e);
> abstract void visitAddExp(AddExp e);
>}
>
>abstract class Expression
>{
> abstract void accept(ExpressionVisitor v);
>}
>
>class IntExp extends Expression
>{
> int value;
>
> void accept(ExpressionVisitor v)
> {
> v.visitIntExp(this);
> }
>}
>
>class AddExp extends Expression
>{
> Expression e1, e2;
>
> void accept(ExpressionVisitor v)
> {
> v.visitAddExp(this);
> }
>}
>
>// Behaviour can now be defined on Expressions
>
>package tools;
>
>class PrettyPrint extends ExpressionVisitor
>{
> void visitIntExp(IntExp e)
> {
> System.out.print(e.value);
> }
>
> void visitAddExp(AddExp e)
> {
> e.e1.accept(this);
> System.out.print(" + ");
> e.e2.accept(this);
> }
>}
>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!
>
>Regards,
>Sam Hwang

-----
Robert C. Martin (Uncle Bob) | email: unclebob@xxxxxxxxxxxxxxxx
Object Mentor Inc. | blog: www.butunclebob.com
The Agile Transition Experts | web: www.objectmentor.com
800-338-6716


"The aim of science is not to open the door to infinite wisdom,
but to set a limit to infinite error."
-- Bertolt Brecht, Life of Galileo
.



Relevant Pages