Cake pattern: how to get all objects of type UserService provided by components

独自空忆成欢 提交于 2019-12-06 01:57:28

You can simply have a list of UserService instances right into UserServiceComponent, and have the base UserService register itself in this list.

trait UserServiceComponent {
  private val _userServices = collection.mutable.Buffer[UserService]()
  def userServices: Seq[UserService] = _userServices.synchronized {
    _userServices.toList // defensive copy
  }
  private def registerUserService( service: UserService ) = _userServices.synchronized {
    _userServices += service
  }

  trait UserService {
    registerUserService( this )

    def getPublicProfile(id: String): Either[Error, User]
  }

  val mainUserService: UserService
}

trait DefaultUserServiceComponent extends UserServiceComponent { self: UserRepositoryComponent =>
  protected class DefaultUserService extends UserService {
    // NOTE: no need to register the service, this is handled by the base class
    def getPublicProfile(id: String): Either[Error, User] = userRepository.getPublicProfile(id)
  }
  val mainUserService: UserService = new DefaultUserService
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!