阿卡和我正在相互了解.
这是一个名为DemoActor的示例actor:
class DemoActor(magicNumber: Int) extends Actor {
def receive = {
case x: Int => sender() ! (x + magicNumber)
}
}
Run Code Online (Sandbox Code Playgroud)
在建议措施 DOC的部分就指出:"这是一个好主意,为每个演员这有助于尽可能地贴近演员的定义尽可能合适的道具创造的同伴对象的工厂方法." 他们喜欢这样:
object DemoActor {
def props(magicNumber: Int): Props = Props(new DemoActor(magicNumber))
}
Run Code Online (Sandbox Code Playgroud)
问题:为道具方法指定工厂之间有什么区别:
object DemoActor {
def props(magicNumber: Int): Props = Props(classOf[DemoActor], magicNumber)
}
Run Code Online (Sandbox Code Playgroud)
如果你错过了它,差异是Props构造函数的参数:
new DemoActor(magicNumber)
Run Code Online (Sandbox Code Playgroud)
VS
classOf[DemoActor], magicNumber
Run Code Online (Sandbox Code Playgroud)
在Props部分的同一个akka文档页面中,它在使用时也会提到Props(classOf[ActorWithArgs], "arg1"):"在构建Props对象期间验证是否存在匹配的构造函数,如果找不到或找到多个匹配的构造函数,则会导致IllegalArgumentEception ".
那很好,不是吗?!?....
Eri*_*ner 12
那很好,不是吗?!?....
是的,但如果在编译期间可以捕获错误,那就更好了.直接调用构造函数的优点是编译器将捕获没有匹配构造函数的问题,而不是在运行时抛出异常.
这个Props apply方法有趣的是你写的时候:
Props(new DemoActor(magicNumber))
Run Code Online (Sandbox Code Playgroud)
创建Props实例时,不会立即调用actor的构造函数.构造函数调用按名称而不是按值传递.你可以在Props apply方法的签名中看到这个:
def apply[T <: Actor](creator: ? T)(implicit arg0: ClassTag[T]): Props
Run Code Online (Sandbox Code Playgroud)
注意creator参数中的右箭头.这允许创建者构造被推迟,并且可能在远程演员的另一个过程中执行.
这里存在的潜在危险是,如果new操作关闭了作用域并捕获了一个非序列化或不可序列化的值,从而使Props对象也不可序列化.这就是文档建议在actor的伴随对象中执行此操作的原因 - 以最小化关闭不打算序列化的数据的风险.
| 归档时间: |
|
| 查看次数: |
3220 次 |
| 最近记录: |