문제

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?

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top