Skip to content

Strategy

  • Instead of using Records (java class) and Protocols (java interface) to achieve polymorphism, you can use defmulti and defmethod
  • defmulti: create a function that has multiple implementations
  • defmethod: each implementation to be associated with the multi function
  • Dynamic dispatches
  • Strategy
  • It's the function that defines which implementation must be picked for each case
  • This allows polymorphism not only based on the object type, but also on a custom strategy
; function with many implementations
; to strategy must be defined in order to choose which implementation to pick
(defmulti my-fn class) ; use "class" function as strategy

; implementations
(defmethod my-fn
  java.lang.String ; argument that will be passed to the strategy
  [item]
  (println "String:" item))

(defmethod my-fn
  java.lang.Number ; argument that will be passed to the strategy
  [item]
  (println "Number:" item))

;; invoking methods
(my-fn 99)
(my-fn "abc")