Code generator and visitor pattern
Mark Lawrence
breamoreboy at yahoo.co.uk
Sat Jul 17 19:08:22 EDT 2010
On 17/07/2010 20:38, Mick Krippendorf wrote:
> Karsten Wutzke wrote:
>> The visitor pattern uses single-dispatch, that is, it determines
>> which method to call be the type of object passed in.
>
> Say, in Python, I have an object o and want to call one of it's methods,
> say m. Then which of possibly many methods m to call is determined by
> the type of o, and nothing else (at least without further magic) -
> hence, it is single dispatch. The VP uses two single dispatch calls (one
> being a callback) to accomplish double dispatching.
>
> Java has a form of multiple dispatch through function overloading. In
> fact, it's still single dispatch, because which of the targets
> overloaded methods gets called is determined at compile time by the
> staticly known types of the methods parameters, AKA the formal parameter
> types.
>
> Anyway. Although VP *uses* double dispatch, it does not necessarily rely
> on function overloading. In Java the VP is most often implemented like this:
>
> <java>
>
> interface IASTNode {
> void accept(IASTVisitor);
> }
>
> class IfNode implements IASTNode {
> void accept(IASTVisitor visitor) {
> visitor.visit(this);
> }
> }
>
> class ElseNode implements IASTNode {
> void accept(IASTVisitor visitor) {
> visitor.visit(this);
> }
> }
>
> interface IASTVisitor {
> void visit(IfNode node);
> void visit(ElseNode node);
> ...
> }
> class PrettyPrinter implements IASTVisitor {
> public void visit(IfNode n) {
> ...
> }
> public void visit(ElseNode n) {
> ...
> }
> }
>
> </java>
>
> but it could as well be implemented like this:
>
> <java>
>
> interface IASTNode {
> void accept(IASTVisitor);
> }
>
> class IfNode implements IASTNode {
> void accept(IASTVisitor visitor) {
> visitor.visitIfNode(this);
> }
> }
>
> class ElseNode implements IASTNode {
> void accept(IASTVisitor visitor) {
> visitor.visitElseNode(this);
> }
> }
>
> interface IASTVisitor {
> void visitIfNode(IfNode node);
> void visitElseNode(ElseNode node);
> ...
> }
> class PrettyPrinter implements IASTVisitor {
> public void visitIfNode(IfNode n) {
> ...
> }
> public void visitElseNode(ElseNode n) {
> ...
> }
> }
>
> </java>
>
> If Java were *really* a multiple dispatch language, it wouldn't be
> necessary to repeat the accept-code for every subclass. Instead a single
> accept method in the base class would suffice. In fact, with true
> multiple dispatch VP wouldn't even be needed.
>
>
> Regards,
> Mick.
Boilerplate, boilerplate everywhere, but not a beer to drink.
Hope everyone at EuroPython is having a good time.
Kindest regards.
Mark Lawrence.
More information about the Python-list
mailing list