这就是Props为之而生的。using 的优点Props是您可以Processor在运行时将所需的任何参数传递给构造函数,而不是仅限于使用无参数构造函数。
需要注意的一件事Props是它需要一个别名creator参数,所以当你看到Props(new TestActor)那个TestActor时候实际上并没有创建。它是在您传递Propsto时创建的actorOf()。
要将Actors 限制为您的子类型,Processor您可以创建Props.
例如:
trait Processor extends Actor
class MyProps(creat: () ⇒ Processor) extends Props(creat)
object MyProps {
def apply(creator: ⇒ Processor): MyProps = new MyProps(() => creator)
}
你的Event班级会有一个Seq[MyProps]. 这是一个示例测试:
case class Event(
name: String,
channels: Seq[String],
processors: Seq[MyProps]
)
class TestActor(bar: String) extends Processor {
def receive = {
case msg @ _ => println(bar + " " + msg)
}
}
object SeqProps extends App {
override def main(args: Array[String]) {
val system = ActorSystem()
val event = new Event("test", Seq("chan1", "chan2", "chan3"),
Seq(MyProps(new TestActor("baz")),
MyProps(new TestActor("barz"))))
event.processors.foreach { proc =>
system.actorOf(proc) ! "go!"
}
system.shutdown()
}
}
如果您尝试将非传递Processor给MyProps()它将在编译时失败。
scala> class NotProcessor extends Actor {
| def receive = emptyBehavior
| }
defined class NotProcessor
scala> MyProps(new NotProcessor)
<console>:15: error: type mismatch;
found : NotProcessor
required: Processor
MyProps(new NotProcessor)
^