Clojure 多方法与协议 [英] Clojure multimethods vs. protocols

查看:27
本文介绍了Clojure 多方法与协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Clojure 新手,正在寻找有关何时使用协议以及何时使用多方法的具体示例.我知道协议通常面向创建类型层次结构和典型的 OOP 事物,它们是在多方法之后添加到语言中的,并且协议通常具有更好的性能,所以我的问题是:

I'm a Clojure novice and was looking for some concrete examples of when to use protocols and when to use multimethods. I know that protocols are generally geared towards creating a type hierarchy and typical OOP things, that they were added to the language after multimethods, and that protocols generally have better performance so my question is this:

协议是否旨在取代多方法?如果没有,你能举个例子,我将使用多方法而不是协议吗?

推荐答案

Multimethods 更强大也更昂贵,

Multimethods are more powerful and more expensive,

在足够的情况下使用协议,但如果您需要根据从火星看到的月相进行调度,那么多方法是您的最佳选择.

use protocols when they are sufficient but if you need to dispatch based on the phase of the moon as seen from mars then multimethods are your best choice.

协议的存在是为了让简单的东西保持简单,并为 clojure 提供一种方法来生成与等效的 java 非常相同的字节码.似乎大多数人大部分时间都在使用协议.当我需要分派多个参数时,我会使用多方法,尽管我不得不承认这种情况只出现过一次,而且完整的 isa 层次结构使用得更少(我自己).所以简而言之在需要时使用 Multimethods

Protocols exist to allow the simple stuff to stay simple and provide a way for clojure to generate very much the same bytecode that the equivalent java would. It seems that most people use protocols most of the time. I use multimethods when I need to dispatch on more than one argument, though I have to admit that this has only come up once, and full isa hierarchies are used even less often (by me). so in short use Multimethods when you need them

最好的例子在我的经验中,在核心中.clj

the best example In my expierence is right at the start, in core.clj

这篇关于Clojure 多方法与协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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