Clojure:使用Java Interop限制来保持纯度

时间:2015-12-14 16:47:24

标签: java clojure functional-programming

我有一个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时收集每条记录的结果。我的主要限制是DecodeMsgBroadcasterRecordListener接口都由第三方库定义,onMsg返回void。< / p>

如何在保持纯粹的同时收集每个广播的值RecordHandler?我当前的解决方案涉及将向量引用传递给RecordHandler的初始化并使用alterconj,但这是修改引用,这似乎违反了不修改外部状态的想法。

(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)))

0 个答案:

没有答案