多个特质mixin和Actors的问题

时间:2012-04-22 22:09:10

标签: scala inheritance actor mixins traits

trait A extends Actor {
  private val s = Set[Int]()

  override def act() {
    loop {
      react {
        // case code that modifies s
      }
    }
  }
}

trait B extends Actor {
  private val t = Set[String]()

  override def act() {
    loop {
      react {
        // case code that modifies t
      }
    }
  }
}

val c = new C with A with B //...?

我真正想要的是B.act() and C.act()的某种自动组合,但是对于特质混合,只会调用B.act()。有没有一种简单的方法可以实现这一目标?

编辑:这是我找到的half-solution。我说“一半”是因为原始特征不再延伸Actor,而C with A with B需要被定义为一个类而不是动态混合。也许我应该把它称为'四分之一解决方案'?

2 个答案:

答案 0 :(得分:1)

也许你可以制作一个将消息转发到其他Actors列表的特性,这样你就不必修改AB

trait C extends Actor {
  private val acts: Seq[Actor] = Seq(new A{}, new B{})

  override def act() {
    acts foreach (_.start)
    loop {
      react { case x => acts foreach { _ ! x } }
    }
  }
}

当然,当您实例化时,您可以将acts抽象或用其他集覆盖它。

答案 1 :(得分:1)

扩展Actor类:

import actors.Actor

class MixableActor extends Actor {
  protected var acts = List[PartialFunction[Any, Unit]]()

  final override def act() {
    loop {
      react {
        acts.reduce((a, b) => a orElse b)
      }
    }
  }

  final def receive(act: PartialFunction[Any, Unit]) {
    acts = act :: acts
  }
}

示例代码:

abstract class Node extends MixableActor {
  ...
}

trait User extends MixableActor {
  val files = scala.collection.mutable.Set[Data]()
}

trait Provider extends User {
  receive({
    case ("provide", file: Data) =>
      provide(file)
  }: PartialFunction[Any, Unit])
}

trait Consumer extends User {
  receive({
    case ("consume", file: Data) =>
      consume(file)
  }: PartialFunction[Any, Unit])
}

样本用法:

val provider = new Node with Provider
val consumer = new Node with Consumer
val provider_and_consumer = new Node with Provider with Consumer