作曲演员
我已经实现了可添加到 Actor 的 Listenable/Listener 特征。我想知道是否可以将这种风格的特征附加到演员身上,而不必显式调用 listenerHandler 方法?
我也期待在 Akka 库中找到这个功能。我是否遗漏了某些内容,或者 Akka 是否有某种原因不包含此内容?
trait Listenable { this: Actor =>
private var listeners: List[Actor] = Nil
protected def listenerHandler: PartialFunction[Any, Unit] = {
case AddListener(who) => listeners = who :: listeners
}
protected def notifyListeners(event: Any) = {
listeners.foreach(_.send(event))
}
}
class SomeActor extends Actor with Listenable
{
def receive = listenerHandler orElse {
case Start => notifyListeners(Started())
case Stop => notifyListeners(Stopped())
}
}
I've implemented a Listenable/Listener trait that can be added to Actors. I'm wondering if it's possible to attach this style of trait to an actor without it having to explicitly call the listenerHandler method?
Also I was expecting to find this functionality in the Akka library. Am I missing something or is there some reason that Akka would not not include this?
trait Listenable { this: Actor =>
private var listeners: List[Actor] = Nil
protected def listenerHandler: PartialFunction[Any, Unit] = {
case AddListener(who) => listeners = who :: listeners
}
protected def notifyListeners(event: Any) = {
listeners.foreach(_.send(event))
}
}
class SomeActor extends Actor with Listenable
{
def receive = listenerHandler orElse {
case Start => notifyListeners(Started())
case Stop => notifyListeners(Stopped())
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不直接扩展
Actor
,或者如果您希望非 Actor 也可监听,请创建一个 ListenableActor 来扩展具有 Listenable 的 Actor ?然后,您将像上面所做的那样覆盖 Actor 中的
receive
(除非您还想调用super.receive
,不是吗?--您会只是想修改传入的函数)。Why not extend
Actor
directly, or if you want non-Actors to be Listenable also, create a ListenableActor that extends Actor with Listenable?You then would override
receive
in Actor as you've done above (except you'd want to callsuper.receive
also, wouldn't you?--you'd just want to modify the function that's passed in).我建议您扩展 Actor 并使用
抽象覆盖
。I suggest you extend Actor and use an
abstract override
.为什么我以前没有见过这个问题,呃,好吧,迟到总比没有好:
http://doc.akka.io/docs/akka/snapshot/scala/routing.html
Why haven't I seen this question before, erm, well, better late than never:
http://doc.akka.io/docs/akka/snapshot/scala/routing.html
这是一个解决方案(Beginning Scala 示例的修改版本):
Here is a solution (a modified version of the example from Beginning Scala):
Akka 对此有内置支持:https://github.com/jboner/akka/blob/release-1.2/akka-actor/src/main/scala/akka/routing/Listeners.scala
There is built-in support for this in Akka: https://github.com/jboner/akka/blob/release-1.2/akka-actor/src/main/scala/akka/routing/Listeners.scala