我是一位经验丰富的 Java 程序员,我开始开发基于 actor 的 Scala 应用程序。在我目前正在开发的应用程序中,我必须处理表现出自主和反应行为的 Sender Actor 的实现。场景如下(伪代码):
Actor Sender{
Active behavior (must be active once the actor boots):
do-in-sequence{
send to Stdout A
send to Stdout B
send to Stdout C
send stop to Stdout and then exit
}
Reactive behavior (must be active once the actor boots):
as soon as received stop from StopNotifier -> send stop to Stdout and then exit
}
}
Actor Stdout{
Purely reactive behavior (i.e. wait for msg){
as soon as received A -> print A
as soon as received B -> print B
as soon as received C -> print C
as soon as received stop from Sender -> exit
}
}
Actor StopNotifier
Purely active behavior {
compute, and when some condition is met -> send stop to Sender
}
我的问题是:对于需要集成自主性和反应性(如本文所述)的 Scala 演员来说,表达自主行为的最佳方式是什么?
换句话说,在上面的示例中,对 Sender 演员进行编码的最佳方式/风格是什么?
我想出了一个解决方案(在下面报告),但由于我不是 scala 大师(还 :))我想知道我所实施的是否可以在更好/更好的解决方案中得到改进。
case object START
case object A
case object B
case object C
case object SENT_A
case object SENT_B
case object ACK_A
case object ACK_B
case object ACK_C
case object STOP
class Sender(stdout: Stdout) extends Actor {
def act() {
self!START
while (true){
receive {
case START =>
stdout!?A
self!SENT_A
case SENT_A =>
stdout!?B
self!SENT_B
case SENT_B =>
stdout!?C
stdout!?STOP
exit()
case STOP => {
Console.println("[Sender:]Received STOP, terminating")
stdout!?STOP
exit()
}
}
}
}
}
class Stdout() extends Actor {
def act() {
while (true) {
receive{
case A =>
Console.println("[Stdout:]A")
reply(ACK_A)
case B =>
Console.println("[Stdout:]B")
reply(ACK_B)
case C =>
Console.println("[Stdout:]C")
reply(ACK_C)
exit()
case STOP =>
Console.println("[Stdout:]Received STOP, terminating")
exit()
}
}
}
}
class StopNotifier(sender: Sender) extends Actor {
def act() {
/*
* The idea is that the StopNotifier should send a STOP message to the Sender
* when a certain condition is met.
* The sleep used here is just a semplification, since the detection of such
* a condition is not relevant for the example.
*/
Thread.sleep(200)
Console.println("[StopNotifier:]Sending STOP to sender")
sender ! STOP
exit()
}
}
object app extends Application {
val stdout = new Stdout
stdout.start
val sender = new Sender(stdout)
sender.start
val stopNotifier = new StopNotifier(sender)
stopNotifier.start
}
特别是在我当前的实现中困扰我的是,为了能够对从 StopNotifier 接收到的 STOP 消息迅速做出反应,我需要在 Sender 的每个执行步骤(即在将 A、B 发送到 Stdout 演员)。在我看来,做事情的正确方法太棘手了:)。
我还尝试使用其他 Scala 语言结构(例如异步发送、反应等)开发其他解决方案,但在我看来,它们似乎受到其他问题/技巧的影响。
有没有人有更好的解决方案来处理 scala 演员中自治和反应行为的整合?