
;; 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
| Можно избежать жесткой зависимости отправителя запроса от его получателя, при этом запросом начинает обрабатываться один из нескольких объектов. Объекты-получатели связываются в цепочку, и запрос передается по цепочке, пока какой-то объект его не обработает. |