修改参数作为多方法的一部分

丹·普林斯

编写多方法来修改传入参数作为调度的一部分的惯用方式是什么?

在这种情况下,我要删除其中一个参数:

(defmulti do-update ???)

(defmethod do-update :set-cursor [state x y]
  (assoc state :cursor [x y]))

(defn post [action & args]
  (swap! some-state do-update action args))

(post :set-cursor 0 0)

dispatch-fn这里将负责读取action关键字转发(cons state args)上作为方法的参数。

此方法的替代方法是创建调度图。

(defn set-cursor [state x y])

(def handlers
  {:set-cursor set-cursor})

(defn dispatch [action & args]
  (let [handler (action handlers)]
    (apply swap! some-state handler args)))

但是,最好在没有映射的情况下针对它们的相应操作自动注册这些处理程序。

米歇尔·马尔奇克(MichałMarczyk)

多方法设计的一部分是,方法接收与分派函数相同的参数。如果这些方法对仅用于分派的某些参数不感兴趣,那么在方法实现中忽略它们是完全可以的,并且一点也不奇怪:

(def some-state (atom {:cursor [-1 -1]}))

(defmulti do-update
  (fn [state action x y]
    action))

;; ignoring the action argument here:
(defmethod do-update :set-cursor [state _ x y]
  (assoc state :cursor [x y]))

;; added apply here to avoid ArityException in the call to do-update:
(defn post [action & args]
  (apply swap! some-state do-update action args))

(post :set-cursor 0 0)

@some-state
;= {:cursor [0 0]}

注意,dispatch参数在这里排在第二位,以方便do-updatewith的使用swap!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章