Visitor Pattern: Traversing tree elements in client or visitor

别说谁变了你拦得住时间么 提交于 2019-12-11 09:13:19

问题


Good morning stackoverflow,

I'm currently implemeting a visitor pattern on something like an AST. Now my question is, how do I iterate through the elements ?

I think its somewhat more logical to just return the object to the visitor and let the visitor traverse from there on. Because you're keeping up flexibility , when you would like to traverse the object in different ways.

On the other side one could say, the visitor shouldn't concern about the structure of the object. So in case the object changes, you don't have to change the visitor too.

Are there any general recommadations how to solve this? I've got two books about Visitor Patterns but both are not dealing with the question how to deal with more complex nodes.

Regads toebs


回答1:


It seems pretty straightforward for a tree structure. The accept method in a node could look like this:

void accept(Visitor visitor) {
    visitor.visitMyTypeOfNode(this);
    for each child {
        child.accept(visitor);
    }
}

Obviously you need to consider if this makes sense in the overall architecture of your application.



来源:https://stackoverflow.com/questions/20044505/visitor-pattern-traversing-tree-elements-in-client-or-visitor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!