0
interface ICarElementVisitor {
    void visit(Engine engine);
}

interface ICarElement {
    //want to use this
    void accept(ICarElementVisitor visitor); // CarElements have to provide accept().
}

static class Engine implements ICarElement {
    ...
    //want to avoid using this
    public void accept(ICarElementVisitor visitor) {
        visitor.visit(this);
    }
}
...
public void accept(ICarElementVisitor visitor) {
    for (ICarElement elem : elements) {
        elem.accept(visitor);
    }
    visitor.visit(this);
}
    ...
static class CarElementDoVisitor implements ICarElementVisitor {

    public void visit(Engine engine) {
        System.out.println("Starting my engine");
    }

}

Is there a way to avoid using method for self invoke inside every element in Visitor Pattern and use global method of parent class? Or if can i pass parent object and know what instance is that object without instanceof if or switch?

Adam Michalski
  • 1,722
  • 1
  • 17
  • 38
  • AFIAK not in Java. Your compiler needs to make the early binding of the visitor method and for that matter it needs to know the exact type. You can see more about how Java chooses the right method at compile time [here](http://stackoverflow.com/a/10901357/697630). – Edwin Dalorzo May 05 '15 at 13:37
  • Why do you want to avoid this? It's a polymorphic call, which is part of the essence of the Visitor pattern. `visitor.visit(this)` allows easily extending new functionality, i.e., you can code up new Visitors and you won't ever have to touch the `ICarElement` code. Using `instanceof` means for every additional type of Visitor, you'd have to add a new check for `instanceof`. I'm guessing you haven't understood the problem that Visitor solves, because what you're proposing allows the problem to come back. – Fuhrmanator May 06 '15 at 12:21
  • I dont want to use visitor.visit(this); in every class i want to visit – Adam Michalski May 07 '15 at 06:56

1 Answers1

0

I think you have to do that to be sure to have the corresponding visit() method for all the ICarElement in all ICarElementVisitor

So if you write an new ICarElement, let say IWheel, one year later and you don't remember all visitors already existing you will be oblige to implement the accept(ICarElementVisitor) method doing visitor.visit(this); doing that the complier will say: "there is no method visit(IWheel) in ICarElementVisitor!" so you will add the visit(IWheel) in the ICarElementVisitor interface and the compiler will say "CarElementDoVisitor don't implement all methods of ICarElementVisitor!" and you will implement visit(IWheel) in CarElementDoVisitor so you are sure to avoid regression.

I think that the point of doing that and it's not useless, in fact that a good thing.

kwisatz
  • 1,266
  • 3
  • 16
  • 36