I was doing some homework today with the visitor-pattern, and i made a visitor that looked somewhat like this (edited sample code from wikipedia):
class CarElementPrintVisitor implements CarElementVisitor {
public void visit(CarElement element) {
if (element.getClass() == Wheel.class)
{
return visit((Wheel)element);
}
else if (element.getClass() == Engine.class)
{
return visit((Engine)element);
}
else if (element.getClass() == Body.class)
{
return visit((Body)element);
}
else //if (v.getClass() == Car car.class)
{
return visit((Car)element);
}
}
public void visit(Wheel wheel) {
System.out.println("Visiting " + wheel.getName() + " wheel");
}
public void visit(Engine engine) {
System.out.println("Visiting engine");
}
public void visit(Body body) {
System.out.println("Visiting body");
}
public void visit(Car car) {
System.out.println("Visiting car");
}
}
The “public void visit(CarElement element)” method is kind of ugly (long and needs to be maintained if more CarElements are added) but i want to keep the method, so i tried to do it better.
I ended up trying this out:
public void visit(CarElement element) {
return visit(element.getClass().cast(element));
}
But that just returns “visit(CarElement element)”, even though element.getClass() returns the correct class, so it ends up in a infinite loop.
Does anyone know how to do, what i’m trying to do? (If it is even possible, i’m not sure).
You missed what makes the beauty of the visitor pattern: the
accept(CarElementVisitor)method that must be in the CarElement interface, and which calls the visitor back with itself, using the approriate type. Re-read the wikipedia article.