2017-09-29 86 views
1

我想使用akka actor實施CRUD操作。我是一個新的阿卡,所以不知道阿卡演員的設計基礎。如何擴展超級演員在akka中的行爲

我想分享多個子角色中的akka​​角色的行爲。

我想保存並刪除學生,老師和其他實體的杉木例子。

我已經創建了男演員StudentDao.scala

class StudentDao extends Actor with ActorLogging{ 

override def Receive = { 

    case Add(student) => 
     // Add to database 
    case Delete => 
     //Delete from database  
    // Some other cases related to Student entity 
    } 
} 
case object StudentDao{ 
    case class Add(user : Student) 
    case class Delete(id : String) 
} 

同我有演員的TeacherDao.scala

class TeacherDao extends Actor with ActorLogging{ 

override def Receive = { 

    case Add(teacher) => 
     // Add to database 
    case Delete => 
     //Delete from database  
    // Some other cases related to teacher entity 

    } 
} 

object TeacherDao{ 
    case class Add(user : teacher) 
    case class Delete(id : String) 
} 

我想兩個DAO抽象的刪除方法。 所以我要創建BaseDao.scala

class BaseDao extends Actor with ActorLogging{ 

    override def Receive = { 

    case Delete => 
     //Delete from database dao.delete 
    } 

我怎麼能抽象的使用基本演員。

回答

0

您可以創建基本演員一個特點,具有共同的接收功能orElse另外一個有子者,以實現:

trait BaseActor extends Actor { 

    override def receive: Receive = commonReceive orElse handleReceive 

    def commonReceive: Receive = { 
    case CommonMessage => // do something 
    } 

    def handleReceive: Receive 
} 

然後你的子參與者只需要執行handleReceive:

class SubActor extends BaseActor { 

    override def handleReceive: Receive = { 
    case SpecificMessage => // do something 
    } 
} 
1

orElse是延長演員的行爲方式,因爲一個演員的Receive簡直是PartialFunction[Any, Unit]的別名。以下是您的使用案例的具體說明。

首先,定義必須與演員混合的特徵中的基本行爲。爲避免重複,請將Delete案例類移入此特徵的伴隨對象。

trait BaseDao { this: Actor with ActorLogging => 
    import BaseDao._ 

    def baseBehavior: Receive = { 
    case Delete(id) => 
     log.info(s"Deleting $id from db") 
     // delete from db 
    } 
} 

object BaseDao { 
    case class Delete(id: String) 
} 

然後,混合上述特質到您的其他演員和鏈orElse行爲。請注意,我創建了虛擬StudentTeacher個案類,以便編譯此代碼。 StudentDao

class StudentDao extends Actor with ActorLogging with BaseDao { 
    import StudentDao._ 

    def studentBehavior: Receive = { 
    case Add(student) => 
     log.info(s"Adding student: $student") 
    // some other cases related to Student 
    } 

    def receive = studentBehavior orElse baseBehavior 
} 

object StudentDao { 
    case class Add(user: Student) 
} 
case class Student(name: String) 

而且TeacherDao

class TeacherDao extends Actor with ActorLogging with BaseDao { 
    import TeacherDao._ 

    def teacherBehavior: Receive = { 
    case Add(teacher) => 
     log.info(s"Adding teacher: $teacher") 
    // some other cases related to Teacher 
    } 

    def receive = teacherBehavior orElse baseBehavior 
} 

object TeacherDao { 
    case class Add(user: Teacher) 
} 
case class Teacher(name: String)