Clojure多方法vs.协议 [英] Clojure multimethods vs. protocols
问题描述
我是一个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:
协议是否代替多方法?如果没有,你能给我一个例子,我将使用多方法而不是协议?
推荐答案
功能强大且更昂贵,
在足够时使用协议,但如果您需要根据月球的阶段那么多方法是你最好的选择。
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生成非常相同的字节码, 。大多数人似乎大多数时候都使用协议。我使用multimethods当我需要分派多个参数,虽然我不得不承认,这只是一次,完全 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
最好的例子在我的expierence是在开始,在 core.clj
the best example In my expierence is right at the start, in core.clj
这篇关于Clojure多方法vs.协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!