Created
September 5, 2016 06:39
-
-
Save Centaur/e8201ed565aae9673f39109dc19cbfc9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.snippets | |
import scala.collection.mutable.ListBuffer | |
import scala.reflect.ClassTag | |
trait Event[T] { | |
} | |
trait EventListener[T] { | |
def onEvent(event: Event[T]) | |
} | |
trait Listenable[T] { | |
val name: String | |
val listeners: ListBuffer[EventListener[T]] | |
} | |
object Event { | |
var cachedListenables: Map[ClassTag[_], Listenable[_]] = Map() | |
implicit def eventIsListenable[T: ClassTag]: Listenable[T] = { | |
val typ = implicitly[ClassTag[T]] | |
cachedListenables.get(typ) match { | |
case None => | |
val newVal = new Listenable[T] { | |
override val name: String = s"Listeners of Event[${implicitly[ClassTag[T]]}]" | |
override val listeners: ListBuffer[EventListener[T]] = ListBuffer() | |
} | |
cachedListenables = cachedListenables.updated(typ, newVal) | |
newVal | |
case Some(l) => l.asInstanceOf[Listenable[T]] | |
} | |
} | |
} | |
object TypedEvents { | |
def dispatchEvent[T](event: Event[T])(implicit ev: Listenable[T]): Unit = { | |
val listeners = ev.listeners | |
println(s"Invoking ${ev.name} , ${ev.hashCode}(相同类型的Event应使用同一个listener集合)") | |
listeners.foreach(listener => { | |
listener.onEvent(event) | |
}) | |
} | |
def main(args: Array[String]): Unit = { | |
import Event._ | |
dispatchEvent(new Event[Int] {}) | |
dispatchEvent(new Event[Int] {}) | |
dispatchEvent(new Event[Int] {}) | |
dispatchEvent(new Event[String] {}) | |
dispatchEvent(new Event[String] {}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment