【发布时间】:2015-02-05 06:15:55
【问题描述】:
我在 Scala 2.10 中使用蛋糕模式根据一些业务逻辑向我的演员注入所需的特征:
我有几种类型的事件:
sealed abstract class Event(val timeStamp:Long)
case class StudentEvent(override val timeStamp:Long, studentId:Long) extends Event(timeStamp:Long)
case class TeacherEvent(override val timeStamp:Long, teacherIdId:Long) extends Event(timeStamp:Long)
现在我有了为每种类型的事件实现动作的特征:
摘要:
trait Action[T <: Event] {
def act[T](event:T):Unit
}
还有两个实现:
trait StudentAction extends Action[StudentEvent]{
override def act[StudentEvent](event:StudentEvent):Unit = println(event)
}
和
trait TeacherAction extends Action[TeacherEvent]{
override def act[TeacherEvent](event:TeacherEvent):Unit = println(event)
}
现在我的演员:
class ActionActor[T <: Event] extends Actor{
self:Action[T]=>
override def receive= {
case msg: T => act(msg)
case _ => println("Unknown Type")
}
}
我以这种方式注入所需的特征:
val actionActor = system.actorOf(Props(new ActionActor[StudentEvent] with StudentAction))
actionActor ! StudentEvent(1111L,222L)
编译时出现错误:
Warning:(14, 14) abstract type pattern T is unchecked since it is eliminated by erasure
case msg:T => act(msg)
^
我知道我需要以某种方式使用 TypeTag,但我不明白该怎么做。
请帮忙。
更新:
实际上,我有 10 种类型的事件,它们从我需要处理的事件扩展而来。
我想在单独的 trait 中为每个事件实现业务逻辑,因为混合所有 10 个事件处理函数会给我数百(如果不是数千)行代码。
我不想为每个事件创建不同的 Actor 类型。例如:
class Event1Actor extend Actor{
def receive ={
case Event1(e) => //event1 Business Logic
}
}
class Event2Actor extend Actor{
def receive ={
case Event2(e) => //event2 Business Logic
}
}
和同一个Event3Actor、Event4Actor等......
这样的代码在我看来很难看,因为我需要在每个 Actor 内部实现业务逻辑。
我正在寻找某种基于设计模式的通用解决方案,例如策略模式。
【问题讨论】:
标签: scala dependency-injection akka