协议和协议之间的差异药剂中的行为 [英] Difference between protocol & behaviour in elixir
问题描述
行为定义回调&协议定义没有签名的方法。实现协议的模块应为所有这些方法提供定义。使用行为的模块也是如此。语义上有什么区别?
Behaviours define callbacks & protocols define methods without signatures. Modules implementing a protocol should give definition for all those methods. Same for modules using a behaviour. What is the semantic difference?
我能想到的一个区别是,一个协议只能为单个类型实现一次,因为我们可以根据自己的要求多次为模块实现行为。我清楚何时使用什么。
One difference I can think of is, a protocol can be implemented for a single type only once where as we can implement a behaviour for a module multiple times based on our requirements. I am clear with when to use what. Is there any other difference other than this?
推荐答案
协议是基于类型/数据的多态性。当我调用 Enum.each(foo,...)
时,具体枚举由 foo
的类型确定
Protocol is type/data based polymorphism. When I call Enum.each(foo, ...)
, the concrete enumeration is determined from the type of foo
.
行为是一种无类型的插件机制。当我调用 GenServer.start(MyModule)
时,我显式传递了 MyModule
作为插件,以及通用代码 GenServer
会在需要时调用此模块。
Behaviour is a typeless plug-in mechanism. When I call GenServer.start(MyModule)
, I explicitly pass MyModule
as a plug-in, and the generic code from GenServer
will call into this module when needed.
这篇关于协议和协议之间的差异药剂中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!