如何在蛋糕模式的另一个组合中重用依赖对象

How reuse a dependency object in another composition in cake pattern

我有两个服务 类 如下所示...

用户服务:

class UserService { dao: UserGroupDao =>
 ...
 def read(userId: String): Future[Option[User]] = dao.readUser(userId)
 ...
}

团体服务:

class GroupService {dao: UserGroupDao =>
 def createGroup(group: Group): Future[Either[String, String]]) = {
  val userService = new UserService() with UserMysqlDao
  userService.read(group.ownerId) map {
   case Some(u) => dao.createGroup(group)
   case None => Left("Invalid User!")
  }
 }
 ...
}

我只是在验证群组的所有者是否是有效用户。为此,我通过硬编码的 Dao 实现重用了 userService.read 方法,即 UserMySqlDao.
在这里,我的问题不是提供硬编码的 Dao Impl,而是如何使用 groupservice 的 dao 对象。因为 UserService 和 GroupService 的类型相同。

我尝试使用以下

val userService = new UserService with dao

但这失败了。因此,我是 scala 的新手,不太清楚为什么会失败。如果有人能说明为什么这是不合法的,那将会很有帮助。

提前致谢:)

如果我理解你的问题,你正在寻找使用 Cake Pattern 声明多个依赖项的解决方案。

常用的解决方案是定义一个新类型,一个组件,它包含对您需要的所有依赖项的引用。在您的具体情况下,故事如下。

trait GroupServiceComponent {
  val userService: UserService
  val userGroupDao: UserGroupDao

  class GroupService {
    def createGroup(group: Group): Future[Either[String, String]]) = {
      userService.read(group.ownerId) map {
        case Some(u) => userGroupDao.createGroup(group)
        case None => Left("Invalid User!")
      }
    }
  }
}

如果您需要更多信息,请告诉我。

我只是想玩一玩,看看我能编译出什么。不确定这是一个好的解决方案,甚至是好的风格,但我的想法是让 GroupService 依赖于 UserService,这就是 dao public.

class UserService { d: UserGroupDao =>
  val dao = d
  def read(userId: String): Future[Option[User]] = dao.readUser(userId)
}

class GroupService { svc: UserService =>
  def createGroup(group: Group): Future[Either[String, String]] = {
    svc.read(group.ownerId) map {
      case Some(_) => svc.dao.createGroup(group)
      case None => Left("Invalid User!")
    }
  }
}