Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Created June 4, 2013 21:44
Show Gist options
  • Save tyrcho/5709877 to your computer and use it in GitHub Desktop.
Save tyrcho/5709877 to your computer and use it in GitHub Desktop.
object Events {
object Event {
def build(typee: String) = {
typee match {
case "foo" => new FooEvent
case "bar" => new BarEvent
}
}
}
class Event(val typee: String)
class FooEvent extends Event("foo")
class BarEvent extends Event("bar")
type EventProcessor[-E <: Event] = E => Unit
val postProcess: EventProcessor[Event] = e =>
println("do something with type " + e.typee)
def sequence[E <: Event](processors: EventProcessor[E]*): EventProcessor[E] = e =>
for (p <- processors) {
p(e)
}
def postProcessF[E <: Event](process: EventProcessor[E]) = sequence(process, postProcess)
trait Processors[E <: Event] {
def processors: Seq[EventProcessor[E]]
}
object Executor {
def process[E <: Event](ev: Processors[E]): EventProcessor[E] = e =>
ev.processors.foreach(_(e))
}
object FooEventProcessor extends EventProcessor[FooEvent] {
def apply(event: FooEvent) = {
println("Foo processing")
}
}
object BarEventProcessor extends EventProcessor[BarEvent] {
def apply(event: BarEvent) = {
println("Bar processing")
}
}
}
import Events._
object Main extends App {
object FooProcessors extends Processors[FooEvent] {
def processors = Seq(postProcessF(FooEventProcessor))
}
object BarProcessors extends Processors[BarEvent] {
def processors = Seq(postProcessF(BarEventProcessor))
}
val event: Event = Event.build("bar")
def processorFor[E <: Event](event: E): Processors[E] = event match {
case e: FooEvent => FooProcessors
case e: BarEvent => BarProcessors
}
Executor.process(processorFor(event))(event)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment