Skip to content

Instantly share code, notes, and snippets.

@ordnungswidrig
Created April 28, 2011 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ordnungswidrig/947353 to your computer and use it in GitHub Desktop.
Save ordnungswidrig/947353 to your computer and use it in GitHub Desktop.
Event dispatching and the expression problem
(ns event-expr)
(declare send-event)
(defprotocol PrintEventHandler
(handle-print [this]))
(defprotocol BarEventHandler
(handle-bar [this]))
(defprotocol SomeAspectEventHandler
(handle-some [this]))
;; no in-place event processing
(defrecord FooEvent [data])
;; in-place event processing for BarEventHandler
(defrecord BarEvent [a b c]
BarEventHandler (handle-bar [bar] (send-event (FooEvent. "from bar")))
SomeAspectEventHandler (handle-some [bar] (println "SomeAspect get an BarEvent with a: " a)))
(defn print-event [e]
(println "Event: " e))
(extend-protocol PrintEventHandler
FooEvent (handle-print [this] (print-event this))
BarEvent (handle-print [this] (print-event this)))
(def handlers {PrintEventHandler handle-print
BarEventHandler handle-bar
SomeAspectEventHandler handle-some})
(defn send-event [e]
(doseq [[p m] handlers]
(if (satisfies? p e) (m e))))
(defn run []
(send-event (FooEvent. "foo1"))
(send-event (FooEvent. "foo2"))
(send-event (BarEvent. :bar1-a :bar1-b :bar1-c)))
(defprotocol OddEvenEventHandler
(handle-odd-even [this]))
(defrecord OddEvenEvent [i])
(defrecord EvenEvent [i])
(defrecord OddEvent [i])
(extend-protocol OddEvenEventHandler
OddEvenEvent
(handle-odd-even [{i :i}]
(send-event (EvenEvent. i)))
OddEvent
(handle-odd-even [{i :i}]
(if (zero? i)
(println " ...odd.")
(send-event (EvenEvent. (dec i)))))
EvenEvent
(handle-odd-even [{i :i}]
(if (zero? i)
(println " ...even.")
(send-event (OddEvent. (dec i))))))
(def handlers (merge handlers
{ OddEvenEventHandler handle-odd-even}))
(defn run-odd-even []
(println "7 is... ")
(send-event (OddEvenEvent. 7))
(println "14 is... ")
(send-event (OddEvenEvent. 14)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment