clojure - 结合 Clojure defprotocol 和 defrecord

标签 clojure protocols

据我所知,如果我想定义一个只能由一个 defprotocol 实现的协议(protocol)( defrecord ) ,我还是要先定义协议(protocol),再定义defrecord实现它:

(defprotocol AProtocol
  (a-method [this])
  (b-method [this that]))

(defrecord ARecord [a-field b-field]
  AProtocol
  (a-method [this] ...)
  (b-method [this that] ...))

有没有办法将两者结合起来,也许是一个“匿名”协议(protocol)?

最佳答案

不要这样做。您的记录实现的“私有(private)”或“匿名”协议(protocol)只是用具有更好选择的语言重新发明了一个毫无意义的 OOP 版本。定义一个对您的记录进行操作的常规旧函数;没有理由必须与它们物理连接。

如果您以后想将其重构为协议(protocol)......这很容易!客户端将无法区分,因为协议(protocol)函数调用看起来就像常规函数调用。

关于clojure - 结合 Clojure defprotocol 和 defrecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6627020/

相关文章:

Clojure:列表替换函数

java - Clojure 中的 JOptionPane "adding a window to a container"异常

emacs - 如何使 nrepl-ritz-jack-in 通过 TRAMP/Emacs 远程工作

swift - ArrayLiteralConvertible 仅当元素类型是 Comparable 时?

java - 传输文件的协议(protocol)

arrays - 在 [SomeProtocol] 类型的数组中查找对象的索引

clojure - 通过连接集合创建惰性序列

dictionary - Clojure 迭代一个向量并向前看/向后看

networking - DVR是否使用标准协议(protocol)进行流传输?

swift - 为类创建通用委托(delegate)