Patterns / Behavioral patterns
image

;; Visitor folds into a multimethod dispatching on the node type: a new
;; visitor is a new defmulti, and the elements are never touched

;; Elements — plain maps tagged with their type
(def car
  [{:type :engine}
   {:type :wheel :number 1} {:type :wheel :number 2}
   {:type :wheel :number 3} {:type :wheel :number 4}
   {:type :car}])

;; ConcreteVisitor
(defmulti scan :type)
(defmethod scan :engine [_] (println "scan engine"))
(defmethod scan :wheel  [w] (println (str "scan wheel #" (:number w))))
(defmethod scan :car    [_] (println "scan car"))

;; ConcreteVisitor
(defmulti repair :type)
(defmethod repair :engine [_] (println "repair engine"))
(defmethod repair :wheel  [w] (println (str "repair wheel #" (:number w))))
(defmethod repair :car    [_] (println "repair car"))

;; Client — accept() is just run!
(run! scan car)
(run! repair car)


Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.