本文介绍了阿卡和蛋糕图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑如何使用蛋糕模式来确保我的Actor具有适当的依赖关系。我仍然对此保持警惕,在任何地方都找不到任何示例。我基本上只是在寻找要遵循的教程/资源。

I'm confused how to ensure that my Actors have the appropriate dependencies using the cake pattern. I'm still getting to grips with this, and I can't find any examples anywhere. I'm basically just looking for a tutorial/resource to follow.

干杯,克里斯。

推荐答案

作为依赖项的角色:

trait DBComponent {
   def db: ActorRef // no compile time guarantees

   type K
   type V

   object DBActor {
      case class Put(key: K, value: V)
      case class Get(key: K)
   }

   class DBActor {
      import DBActor._
      val db = scala.collection.mutable.Map.empty[K, V]
      def receive = {
         case Put(k, v) => db.put(k, v)
         case Get(k) => sender ! db.get(k)
      }
   }
}

trait ServiceComponent {
   this: DBComponent =>

   import DBActor._

   // you could be talking to deadLetters for all you know
   def put(k: K, v: V): Unit = db ! Put(k, v)
   def get(k: K): Option[V] = {
      implicit val timeout = Timeout(5 seconds)
      val future = ask(actor, Get(k)).mapTo[Option[V]]
      Await.result(future, timeout.duration)
   }
}

具有依赖项的演员(那里没有什么特别的地方):

Actors having dependencies (where there is nothing special to it):

trait DBComponent {
   def db: DB

   type K
   type V

   trait DB {
      def put(key: K, value: V): Unit
      def get(key: K): Option[V]
   }
}

trait ServiceComponent {
   this: DBComponent =>

   object ServiceActor {
      case class Put(key: K, value: V)
      case class Get(key: K)
   }

   class ServiceActor {
      import ServiceActor._
      def receive = {
         case Put(k, v) => db.put(k, v) // db is in scope
         case Get(k) => sender ! db.get(k)
      }
   }
}

这篇关于阿卡和蛋糕图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:21