I’m trying to figure out the correct approach (and pattern) that my current problem requires. Everything seems to lead me towards the visitor pattern, and wikipedia’s example is almost exactly what I need. However, my issue is that I’m retrieving these CarElements from the database and need to create the correct visitor depending on the type of CarElements I asked for. For example, if I retrieved a list of Windshields I want to pass in a CarElementWashVisitor. It feels like I’m going against the pattern here but I’m not sure what the correct approach is without checking the subclass type. I basically need some way to figure out what to do based on the runtime type of the object(s). Here’s a summarized portion of the wikipedia example that I linked to above:
interface CarElementVisitor {
void visit(Wheel wheel);
void visit(Engine engine);
void visit(Body body);
void visit(Car car);
}
interface CarElement {
void accept(CarElementVisitor visitor); // CarElements have to provide accept().
}
class CarElementPrintVisitor implements CarElementVisitor { /**/ }
class CarElementDoVisitor implements CarElementVisitor { /**/ }
UPDATE:
Turns out that the issue is actually pretty simple (as illustrated by the accepted answer below). Here’s what I was looking for:
class MyVisitor implements CarElementVisitor {
private MyService carwashService;
/* visit(Wheel w), visit(Engine e)... etc */
void visit(Windshield w) {
carwashService.wash(w);
}
}
Would something like this help?
And use here: