When and where to use Visitor Pattern?
- From: "Sam Hwang" <samhng@xxxxxxxxx>
- Date: 22 Apr 2005 09:42:20 -0700
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
.
- Follow-Ups:
- Re: When and where to use Visitor Pattern?
- From: paul campbell
- Re: When and where to use Visitor Pattern?
- From: Daniel Parker
- Re: When and where to use Visitor Pattern?
- From: Robert C . Martin
- Re: When and where to use Visitor Pattern?
- From: Ilja Preuß
- Re: When and where to use Visitor Pattern?
- From: H. S. Lahman
- Re: When and where to use Visitor Pattern?
- From: Remi Bastide
- Re: When and where to use Visitor Pattern?
- From: Calum Grant
- Re: When and where to use Visitor Pattern?
- From: oldbull
- Re: When and where to use Visitor Pattern?
- Prev by Date: Re: agile methods compared?
- Next by Date: Re: When and where to use Visitor Pattern?
- Previous by thread: Q about UML Negative CombinedFragment
- Next by thread: Re: When and where to use Visitor Pattern?
- Index(es):
Relevant Pages
|