0
我正在使用akka與scala進行邏輯電路實現,我需要實現一個導線Actor(例如,對於諸如AND門的組件演員): 導線應該傳輸一個信號,是真是假。使用akka編寫電路(導線)
我正在使用akka與scala進行邏輯電路實現,我需要實現一個導線Actor(例如,對於諸如AND門的組件演員): 導線應該傳輸一個信號,是真是假。使用akka編寫電路(導線)
這是偉大的,你正在學習阿卡,任務是一個好地方開始。
在我們開始之前,有幾件事情 - 您當前的代碼和建模可能會在幾個地方受到質疑。
AddComponent
需要wireName
?你打算通過演員的名字找到電線嗎?通常我們使用ActorRef
而不是他們的名字。StateChange
需要wireName
?真的有關係嗎?我會說狀態傳播可以使用簡單的消息來完成:StateChanged(state: Boolean)
ActorRef
很好。current: Boolean
通常不是一個好主意,我們希望給語義賦予我們的消息,就像您對StateChange
所做的那樣,所以我也會在這裏使用它。一些代碼,我想出了:
import akka.actor.{ActorLogging, Actor, ActorRef}
case class AddComponent(actor: ActorRef)
case class StateChange(state: Boolean)
class Wire(var currentState: Boolean) extends Actor with ActorLogging {
var connections = Set.empty[ActorRef]
def receive: Actor.Receive = {
case AddComponent(actor) =>
connections += actor
case StateChange(state) =>
currentState = state
val connectionsToPropagateTo = connections - sender // Don't propagate back to sender
connectionsToPropagateTo.foreach { component =>
component ! StateChange(currentState) // Send the component a StateChange message.
}
}
}
您可以根據需要簡單地RemoveComponent
和其他的東西擴展此。
我不明白... – user2947615
不明白?你可以詳細說明一下... –