您可以使用closure
机制,以 “内联” 计数器:
(let [c (atom 0)]
(defn new-connection []
{:id (swap! c inc)
:writebuf :ByteBuffer
:readbuf :ByteBuffer})
(defn get-counter []
@c))
(get-counter)
=> 0
(new-connection)
=> {:id 1, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(new-connection)
=> {:id 2, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(get-counter)
=> 2
或者,如果你需要控制计数器开始值:
(defn create-connection-fn [init-counter-value]
(let [c (atom init-counter-value)]
(fn []
{:id (swap! c inc)
:writebuf :ByteBuffer
:readbuf :ByteBuffer})))
(def new-connection (create-connection-fn 10))
(new-connection)
=> {:id 11, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
(new-connection)
=> {:id 12, :writebuf :ByteBuffer, :readbuf :ByteBuffer}
编辑。如果没有理由“隐藏”它,我建议你将计数器定义为分隔变量。
取决于有多少价值,你放在引用透明? – 2013-03-02 01:46:53
是否指在他编辑下面的mobyte的评论,关于'隐藏'柜台? – georgek 2013-03-02 03:01:40
当涉及对象的计数时,您能期待引用透明吗?我怀疑。 – 2013-03-04 04:26:13