本文介绍了结合Clojure defprotocol和defrecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,如果我想定义一个协议( defprotocol ),只有一个 defrecord ,我仍然必须先定义协议,然后定义实现它的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:01