访问者模式的实际优势是什么?有哪些选择? [英] What are the actual advantages of the visitor pattern? What are the alternatives?

查看:130
本文介绍了访问者模式的实际优势是什么?有哪些选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多有关访客模式及其所谓优势的文章.然而,对我来说,在实践中使用它们似乎并没有那么多优势:

I read quite a lot about the visitor pattern and its supposed advantages. To me however it seems they are not that much advantages when applied in practice:

  • 方便"和优雅"似乎意味着很多样板代码
  • 因此,该代码很难遵循.同样,接受"/访问"不是很描述性
  • 如果您的编程语言没有方法重载(即Vala),则代码示例也更为丑陋
  • 通常,在不修改所有类的情况下,通常无法将新操作添加到现有类型层次结构中,因为一旦需要使用其他操作,就需要无处不在的新'accept'/'visit'方法参数和/或返回值(到处更改类是该设计模式应避免的一件事!?)
  • 向类型层次结构中添加新类型需要更改 all 个访问者.此外,访问者不能简单地忽略类型-您需要创建一个空的访问方法(再次创建样板)
  • "Convenient" and "elegant" seems to mean lots and lots of boilerplate code
  • Therefore, the code is hard to follow. Also 'accept'/'visit' is not very descriptive
  • Even uglier boilerplate code if your programming language has no method overloading (i.e. Vala)
  • You cannot in general add new operations to an existing type hierarchy without modification of all classes, since you need new 'accept'/'visit' methods everywhere as soon as you need an operation with different parameters and/or return value (changes to classes all over the place is one thing this design pattern was supposed to avoid!?)
  • Adding a new type to the type hierarchy requires changes to all visitors. Also, your visitors cannot simply ignore a type - you need to create an empty visit method (boilerplate again)

实际上,您要做的只是所有这些工作:

It all just seems to be an awful lot of work when all you want to do is actually:

// Pseudocode
int SomeOperation(ISomeAbstractThing obj) {
    switch (type of obj) {
        case Foo: // do Foo-specific stuff here
        case Bar: // do Bar-specific stuff here
        case Baz: // do Baz-specific stuff here
        default: return 0; // do some sensible default if type unknown or if we don't care
    }
}

我看到的唯一真正的优点(顺便说一句,我在任何地方都没有提到过):访问者模式可能是根据cpu时间实现上述代码段的最快方法(如果您没有使用以下语言的话)以上述伪代码的方式进行双重分派或有效类型比较).

The only real advantage I see (which btw i haven't seen mentioned anywhere): The visitor pattern is probably the fastest method to implement the above code snippet in terms of cpu time (if you don't have a language with double dispatch or efficient type comparison in the fashion of the pseudocode above).

问题:

  • 那么,我错过了访客模式的哪些优势?
  • 可以使用哪些替代概念/数据结构来使上述虚拟代码示例同样快速地运行?

推荐答案

根据经验,我会说向类型层次结构添加新类型需要更改所有访问者"是一个优势.因为它肯定会迫使您考虑在进行某些特定于类型的操作的所有地方添加的新类型.它可以防止您忘记一个....

By experience, I would say that "Adding a new type to the type hierarchy requires changes to all visitors" is an advantage. Because it definitely forces you to consider the new type added in ALL places where you did some type-specific stuff. It prevents you from forgetting one....

这篇关于访问者模式的实际优势是什么?有哪些选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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