
;; Chain of responsibility folds into a sequence of handlers walked by some:
;; the chain stops at the first one that answers, with no next pointers
;; Handlers — each knows its code and what to do
(def rescuers
[{:code 1 :to-help #(println "call firefighters")}
{:code 2 :to-help #(println "call the police")}
{:code 3 :to-help #(println "call an ambulance")}])
;; HandleRequest()
(defn help [code]
(or (some (fn [r]
(when (= code (:code r))
((:to-help r))
true))
rescuers)
(println "nobody handles code" code)))
(help 1) ; call firefighters
(help 3) ; call an ambulance
(help 9) ; nobody handles code 9 — the chain ran out
| Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. |