我已经开始学习 scala 一段时间了,现在正在研究蛋糕图案。我从这里得到了例子
trait UserRepositoryComponent {
def userLocator: UserLocator
trait UserLocator {
def findAll: List[User]
}
}
trait UserRepositoryJPAComponent extends UserRepositoryComponent {
val em: EntityManager
def userLocator = new UserLocatorJPA(em)
class UserLocatorJPA(val em: EntityManager) extends UserLocator {
def findAll = {
println("Executing a JPA query")
List(new User, new User)
}
}
}
trait UserServiceComponent {
def userService: UserService
trait UserService {
def findAll: List[User]
}
}
trait DefaultUserServiceComponent extends UserServiceComponent {
this: UserRepositoryComponent =>
def userService = new DefaultUserService
class DefaultUserService extends UserService {
def findAll = userLocator.findAll
}
}
对我来说,将 JPA 存储库注入服务似乎有太多样板代码。
然而,这段代码可以用更少的行数做同样的事情
trait UserRepository {
def findAll
}
trait JPAUserRepository extends UserRepository {
val em: EntityManager
def findAll = {
em.createQuery
println("find using JPA")
}
}
trait MyService {
def findAll
}
trait MyDefaultService extends MyService {
this: UserRepository=>
}
实例化这两种情况。
val t1 = new DefaultUserServiceComponent with UserRepositoryJPAComponent {
val em = new EntityManager()
}
t1.userService.findAll
val t2 = new MyDefaultService with JPAUserRepository {
val em = new EntityManager
}
t2.findAll
第二种情况使用更少的代码,并使用 DI。你能帮我了解蛋糕图案带来的额外优势吗?