问题描述
这个问题可以帮助您了解我的需求.蛋糕模式:每个实现一个组件,或者一个每个特征的组成部分?
This question may help you understand my needs.Cake pattern: one component per implementation, or one component per trait?
我有一个使用多个UserService实现的Scala应用程序,这些实现将由组件提供.
I have a Scala application using multiple UserService implementations which will be provided by component(s?).
我想知道另一个组件中是否有一种扫描"应用程序的方式,以便我可以检索提供一个实现特征UserService的对象的所有组件的集合?这样我就可以遍历我的蛋糕构建应用程序提供的所有UserService接口?
I wonder if there is a way in another component to "scan" the application so that I can retrieve a set of all components providing an object which implement the trait UserService? So that I can iterate over all the UserService interfaces provided by my cake built application?
我想我可以有一个根据其依赖关系构建UserService列表的组件,但是有可能使该组件在没有任何硬编码依赖关系的情况下构建列表吗?
I guess I can have a component which build a list of UserService according to its dependency, but is it possible to have this component building the list without having any hardcoded dependency?
推荐答案
您可以直接在UserServiceComponent
中拥有一个UserService
实例列表,并在该列表中注册基本UserService
.
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
}
这篇关于蛋糕模式:如何获取组件提供的UserService类型的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!