Visitor Pattern: Traversing tree elements in clien

2019-08-28 03:11发布

问题:

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.