我已经实现了可以添加到 Actors 的 Listenable/Listener trait。我想知道是否可以将这种风格的特征附加到演员而不必显式调用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())
}
}