结合 Clojure defprotocol 和 defrecord [英] Combining Clojure defprotocol and defrecord
问题描述
据我所知,如果我想定义一个只能由一个defrecord
实现的协议(defprotocol
),我仍然需要定义协议首先,然后定义实现它的defrecord
:
As far as I can tell, if I want to define a protocol (defprotocol
) that will only be implemented by one defrecord
, I still have to define the protocol first, then define the defrecord
that implements it:
(defprotocol AProtocol
(a-method [this])
(b-method [this that]))
(defrecord ARecord [a-field b-field]
AProtocol
(a-method [this] ...)
(b-method [this that] ...))
有没有办法将两者结合起来,也许是匿名"协议?
Is there no way to combine the two, perhaps with an "anonymous" protocol?
推荐答案
不要这样做.您的记录实现的私有"或匿名"协议只是用具有更好选择的语言重新发明无意义的 OOP 版本.定义一个对您的记录进行操作的常规旧函数;没有理由必须将其物理连接到它们.
Don't do this. A "private" or "anonymous" protocol that your record implements is just reinventing a pointless version of OOP in a language that has better options. Define a regular old function that operates on your records; there's no reason it has to be physically attached to them.
如果您以后想将其重构为协议……这很容易!客户端将无法分辨其中的区别,因为协议函数调用看起来就像常规函数调用一样.
If you later want to refactor it to be a protocol instead...it's easy! The client won't be able to tell the difference, because protocol function calls look just like regular function calls.
这篇关于结合 Clojure defprotocol 和 defrecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!