Java visitor pattern when type of visitor depends on type of visitee
-
26-10-2019 - |
문제
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 CarElement
s from the database and need to create the correct visitor depending on the type of CarElement
s I asked for. For example, if I retrieved a list of Windshield
s 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?
class FindTheRightVisitorVisitor implements CarElementVisitor {
private CarElementVisitor theVisitor;
... getter etc ...
void visit(Windshield w) {
if (theVisitors == null) {
theVisitors = new CarElementWashVisitor();
}
}
}
And use here:
CarElement root = ...;
CarElementVisitor findIt = new FindTheRightVisitorVisitor();
root.accept(findIt);
CarElementVisitor theRightVisitor = findIt.getTheVisitor();
root.accept(theRightVisitor);