Visitor pattern where the visitors choose how to traverse

Deadly 提交于 2019-12-07 09:51:46

问题


As I understand it, in the typical specification of the Visitor pattern, it is the visited objects that decide how to traverse, and generally, they only support one traversal order. (See, e.g., here or here.)

Is there a name for the same use of double-dispatch, but where the Visitors get to decide how to traverse the object-hierarchy? In my application, a very heterogeneous collection of document-model types is pushing towards visitors for, e.g., export operations. It seems rigid, though, to say that the various processors (visitors) should all traverse in, say, a breadth-first order. Some of them might only be concerned with a subset of the model or may need to deal with parts of the model in a specialized order.

I'm concerned about confusing other developers by using the names from the visitor pattern in a non-standard way. Is there a name for what I'm suggesting?

I'll also ask if there's a reason not to let the visitor control traversal, just in case there's some wisdom in that usual Visitor formulation that I'm missing. The application is in Java if that may be relevant.


回答1:


To keep the design clear, you can encapsulate traversal logic in an Iterator. The visitor or visitees can use the iterator to determine the next node to visit.

In the Visitor example on wikipedia, we see the class Car control the order of visiting as follows:

public void accept(ICarElementVisitor visitor) {    
    for(ICarElement elem : elements) {
        elem.accept(visitor);
    }
    visitor.visit(this);    
}

It would be easy to encapsulate the traversal logic in an ICarElementIterator that returns an ICarElement from its next() method, per the Iterator pattern.



来源:https://stackoverflow.com/questions/24565781/visitor-pattern-where-the-visitors-choose-how-to-traverse

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