8

我已经实现了可以添加到 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())
    }
}
4

5 回答 5

5

为什么不Actor直接扩展,或者如果您希望非 Actors 也可以监听,创建一个 ListenableActor 来扩展具有 Listenable 的 Actor?

然后,您将像上面所做的那样在 Actor 中覆盖receive(除了您还想调用super.receive,不是吗?--您只想修改传入的函数)。

于 2010-03-09T20:51:14.957 回答
2

我建议你扩展 Actor 并使用abstract override.

于 2010-03-10T00:00:44.530 回答
2

为什么我以前没有见过这个问题,嗯,好吧,迟到总比没有好:

http://doc.akka.io/docs/akka/snapshot/scala/routing.html

于 2010-07-21T21:36:41.607 回答
0

这是一个解决方案(Beginning Scala 中示例的修改版本):

import se.scalablesolutions.akka.actor.Actor

case class AddListener(who: Actor)
case class RemoveListener(who: Actor)

class ListenableActor extends Actor {
    private var listeners: List[Actor] = Nil

    def receive = {
        case AddListener(who) => listeners ::= who
        case RemoveListener(who) => listeners.filter(_ ne who)
    }

    protected def notifyListeners(event: Any) = {
        listeners.foreach(_.send(event))
    }
}

class ImplementingActor extends ListenableActor {
    override def receive = {
        super.receive orElse {
            case Message(content) => println(content)
        }
    }
}
于 2010-03-13T17:31:29.563 回答
0

Akka 对此有内置支持:https ://github.com/jboner/akka/blob/release-1.2/akka-actor/src/main/scala/akka/routing/Listeners.scala

于 2011-09-05T13:27:58.327 回答