Κυριακή, 31 Μαρτίου 2013 7:09 πμ
από το μέλος
ikaragkiozoglou
Scala Repository Locator
Below is my implementation of a Dynamic Service Locator
ServiceLocator.scala
import scala.reflect.runtime.{universe => ru}
trait ServiceLocator {
def getService[T](implicit t: ru.TypeTag[T]) : T
def registerService[T](obj: T)(implicit t: ru.TypeTag[T]) : Unit
}
ServiceLocatorImpl.scala
import scala.reflect.runtime.{ universe => ru }
import scala.reflect.runtime.universe.Type
class ServiceLocatorImpl extends ServiceLocator {
val rep = new scala.collection.mutable.HashMap[reflect.runtime.universe.Type, Any]()
private def internalServiceSearch(t: Type): Option[Any] = {
val tpe = t
for {
s <- rep.keys
if (s <:< tpe || s =:= tpe)
} return Some(rep(s))
None
}
def getService[T](implicit t: ru.TypeTag[T]): T = {
val res = internalServiceSearch(t.tpe)
res match{
case None => throw new Exception("Service not found")
case _ => res.get.asInstanceOf[T]
}
}
def registerService[T](obj: T)(implicit t: ru.TypeTag[T]): Unit = {
if (internalServiceSearch((t).tpe) == None) rep.put(t.tpe, obj.asInstanceOf[Any])
}
}