组成演员

时间:2010-03-09 20:31:29

标签: scala actor akka

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

5 个答案:

答案 0 :(得分:5)

为什么不直接扩展Actor,或者如果你想让非Actors成为可监听的,那么创建一个使用Listenable扩展Actor的ListenableActor?

然后你就像在上面那样覆盖了Actor中的receive(除了你也想要调用super.receive,不是吗? - 你只想修改传入的功能)。

答案 1 :(得分:2)

我建议您扩展Actor并使用abstract override

答案 2 :(得分:2)

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

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

答案 3 :(得分: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)
        }
    }
}

答案 4 :(得分:0)