访问者模式接受不识别对象的类
我想使用访问者模式来实现一棵树。因此,我创建了一个主类 Node
和扩展该类的其他类(例如 Node1
、Node2
、Node3
)。在Node
中,我有一个字符串和一个Nodes
的ArrayList
,它是该节点的子节点列表。因此,我实现了一个具有 3 个函数 visit(Node1 x)
的访问者,...在 main
中,我想调用每个节点的接受:
SomeVisitor v = new SomeVisitor();
Node n = makeTree();
Iterator<? extends Node> it = n.children.iterator();
while(it.hasNext()) {
System.out.println(it.next().getClass());
it.next.accept(v);
}
这不起作用,因为即使虽然 .getClass
返回一个特定的类 我的意思是 Node 1 、 2 或 3 ,我得到的错误是 it.next
是一种类型 节点,但我的树中没有任何节点对象,并且我没有实现 访问(节点)
只是访问(节点1,2,3)
I want to use the visitor pattern to implement a tree. So I made a main class Node
and other classes that extends that class (for example Node1
, Node2
, Node3
). In Node
I have a String and an ArrayList
of Nodes
which is a list of children of that node. So I implemented a visitor with 3 functions visit(Node1 x)
, ... and in main
I want to call accept of every node:
SomeVisitor v = new SomeVisitor();
Node n = makeTree();
Iterator<? extends Node> it = n.children.iterator();
while(it.hasNext()) {
System.out.println(it.next().getClass());
it.next.accept(v);
}
this doesn't work because even though .getClass
returns a specific class
I mean Node 1 , 2 or 3 and the error I get is that is it.next
is a type
node but I don't have any node object in my tree , and I didn't implementvisit(Node)
just visit(Node 1,2,3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查访问者模式的描述。应该在基类中声明accept方法,并且每个子类应该通过回调适当的visit方法来重写它:
Check the description of the visitor pattern. The accept method should be declared in the base class, and each subclass should override it by calling back the appropriate visit method:
很难猜测你的问题出在哪里。您应该看一下 wikipedia 上的示例实现。正如您将看到的,该模式不是通过使用扩展来实现的,而是通过使用装饰接口来实现的。
It's hard to guess where your problem is. You should have a look at a sample implementation like the one on wikipedia. As you will see there the pattern is not implemented by using extension but by using decorating interfaces.
您的解决方案是使用访问者模式,但这不是您似乎正在做的事情。
这是你的问题。您必须使用您所调用的相同方法来实现相同的接口。
您还需要将其编写为
@JB Nizet 的解决方案类似,但我认为以从一开始就需要调用的方式编写代码更简单。
Your solution is to use the visitor pattern, which is not what you appear to be doing.
This is your problem. You have to implement the same interface with the same method which what you call.
Also you need to write it as
@JB Nizet's solution is similar, but I think its simpler to write the code in the manner it needs to be called from the start.