开发者

Inherit message handling behaviour

I have some events in my model and some handling logic. I want organize communication logic throw Actors. But how I can inherit handling logic without specifying act() in each concrete class

Simplified example

class Event {}

case class FooEvent(str : String) extends Event
case class BarEvent(i : java.lang.Integer) extends Event

trait FooListener extends Actor {
  def act() {
    react{
      case FooEvent => print("foo received")
    }
  }
}
trait BarListener extends Actor {
  def act() {
    react{
      case BarEvent => print("bar received")
    }
  }
}
class ListensOnlyBar extends BarListener{}

//can't be done: 
//error: overriding method act in trait FooListener of type ()Unit;
//method act in trait BarListener of type ()Unit needs `override' modifier
//class ListensBarAndFoo extends FooListener with BarListener{
class ListensBarAndFoo extends FooList开发者_运维百科ener with BarListener{}


react expects PartialFunction[Any, Unit] and you can nicely compose them together. Here is an example:

type Listener = PartialFunction[Any, Unit]

val foo: Listener = {
  case FooEvent => print("foo received")
}

val bar: Listener = {
  case BarEvent => print("bar received")
}

case class GenericListener(listener: Listener) extends Actor {
  def act() {
    react(listener)
  }
}

GenericListener(bar)
GenericListener(foo orElse bar)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜