简单的演员实现

考虑员工与其人力资源部门之间的沟通。

http://i.stack.imgur.com/7xZNq.jpg

当消息传递给 actor 时,广泛地在以下六个步骤中解释这些:

  1. 员工创造了一种叫做 ActorSystem 的东西。

  2. 它使用 ActorSystem 来创建一个名为 ActorRef 的东西。消息(MSG)被发送到 ActorRef(HR Actor 的代理)。

  3. 演员 ref 将消息传递给 Message Dispatcher

  4. Dispatcher 将消息排入目标 Actor 的 MailBox 中。

  5. 然后 Dispatcher 将 Mailbox 放在一个 Thread 上(下一节将详细介绍)。

  6. MailBox 将消息出列并最终将其委托给实际的 HR Actor 的 receive 方法。

    /** The Main Program consider it as a Employee Actor that is sending the requests  **/

    object EmployeeActorApp extends App{
     //Initialize the ActorSystem
      val actorSystem=ActorSystem("HrMessageingSystem")

     //construct the HR Actor Ref
      val hrActorRef=actorSystem.actorOf(Props[HrActor])

     //send a message to the HR Actor
      hrActorRef!Message

     //Let's wait for a couple of seconds before we shut down the    system
      Thread.sleep (2000) 

     //Shut down the ActorSystem.
      actorSystem.shutdown()

    }  

    /** The HRActor reads the message sent to it and performs action based on the message Type **/
    class HRActor extends Actor {
       def receive  = {
            case s: String if(s.equalsIgnoreCase(`SICK`)) => println("Sick Leave applied”)
            case s: String if(s.equalsIgnoreCase(`PTO`)) => println("PTO applied “)
}

}