游客选择如何穿越的游客模式 [英] Visitor pattern where the visitors choose how to traverse

查看:213
本文介绍了游客选择如何穿越的游客模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据了解,在访问者模式的典型规范中,被访问对象决定如何遍历,通常它们只支持一个遍历顺序。 (例如,参见此处这里。)



是否有同样使用双重调度的名称,但访问者访问决定如何遍历对象层次结构?在我的应用程序中,非常异质的文件模型类型集合正在推动访问者,例如出口业务。不过,似乎很难说,各种处理器(访客)都应该遍历,比如说一个宽度一级的顺序。其中一些可能只关注模型的一个子集,或者可能需要以特定的排序来处理模型的部分。



我担心混淆其他开发人员以非标准方式使用来自访问者模式的名称。有没有我建议的名字?



我还会问,是否有理由不让访客控制遍历,以防万一有一些智慧那个通常的访客表达,我失踪了。

解决方案

为了保持设计清晰,可以将迭代逻辑封装在迭代器中。访客或访问者可以使用迭代器来确定下一个访问节点。



在维基百科的访问者示例中,我们将看到汽车控件的访问顺序如下:

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

将遍历逻辑封装在 ICarElementIterator ,从 next()方法返回 ICarElement ,根据迭代器模式。


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 heterogenous 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 ordre.

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.

解决方案

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.

这篇关于游客选择如何穿越的游客模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆