我有一个Clojure代码片段,它遵循第三方Java库中定义的Observer pattern,如下所示:
(defrecord RecordHandler []
RecordListener
(onMsg [this msg] (getValue msg)))
(defn read
[file]
(let [decoder (Decode.)
broadcaster (MsgBroadcaster. decoder)
handler (RecordHandler.)]
(.addListener broadcaster handler)
(.run broadcaster file)))
我希望能够在调用onMsg
时收集每条记录的结果。我的主要限制是Decode
,MsgBroadcaster
和RecordListener
接口都由第三方库定义,onMsg
返回void
。< / p>
如何在保持纯粹的同时收集每个广播的值RecordHandler
?我当前的解决方案涉及将向量引用传递给RecordHandler
的初始化并使用alter
和conj
,但这是修改引用,这似乎违反了不修改外部状态的想法。
(defrecord RecordHandler [memo]
RecordListener
(onMsg [this msg]
(dosync
(alter memo conj (getValue msg))))
(defn read
[file]
(let [decoder (Decode.)
broadcaster (MsgBroadcaster. decoder)
memo (ref [])
handler (RecordHandler. memo)]
(.addListener broadcaster handler)
(.run broadcaster file)))