我正在尝试找出当前问题所需的正确方法(和模式)。一切似乎都引导我走向访客模式,维基百科的 example几乎正是我所需要的。但是,我的问题是,我正在从数据库中检索这些 CarElement
,并且需要根据我要求的 CarElement
类型创建正确的访问者。例如,如果我检索了 Windshield
列表,我想传入 CarElementWashVisitor
。感觉就像我在这里违背了模式,但在不检查子类类型的情况下,我不确定正确的方法是什么。我基本上需要某种方法来根据对象的运行时类型确定要做什么。以下是我上面链接到的维基百科示例的摘要部分:
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 { /**/ }
更新:
事实证明,这个问题实际上非常简单(如下面接受的答案所示)。这就是我正在寻找的内容:
class MyVisitor implements CarElementVisitor {
private MyService carwashService;
/* visit(Wheel w), visit(Engine e)... etc */
void visit(Windshield w) {
carwashService.wash(w);
}
}
最佳答案
这样的事情会有帮助吗?
class FindTheRightVisitorVisitor implements CarElementVisitor {
private CarElementVisitor theVisitor;
... getter etc ...
void visit(Windshield w) {
if (theVisitors == null) {
theVisitors = new CarElementWashVisitor();
}
}
}
并在此处使用:
CarElement root = ...;
CarElementVisitor findIt = new FindTheRightVisitorVisitor();
root.accept(findIt);
CarElementVisitor theRightVisitor = findIt.getTheVisitor();
root.accept(theRightVisitor);
关于当访问者类型取决于访问者类型时,Java 访问者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6823525/