当访问者类型取决于访问者类型时,Java 访问者模式
我试图找出我当前问题所需的正确方法(和模式)。一切似乎都引导我走向访问者模式,维基百科的 示例 几乎正是我所需要的。但是,我的问题是,我正在从数据库中检索这些 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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的事情会有帮助吗?
并在这里使用:
Would something like this help?
And use here: