关于蛋糕图案的问题
蛋糕模式
文章 建议使用特征作为命名空间:
trait UserRepositoryComponent {
val userRepository: UserRepository
class UserRepository {...}
}
trait UserServiceComponent {this: UserRepositoryComponent =>
val userService: UserService
class UserService {...}
}
class Context extends UserServiceComponent with UserRepositoryComponent {
val userRepository = new UserRepository
val userService = new UserService
}
但是,如果我们可以执行以下操作,我们真的需要这些“命名空间特征”(UserServiceComponent
和 UserRepositoryComponent
)吗?
trait UserRepository {...}
trait UserService {this: UserRepository =>
...
}
class Context extends UserRepositoryImpl with UserService
所以,我的问题是我们何时以及为什么需要蛋糕模式中的“命名空间”特征。
The Cake Pattern
article suggests using traits as namespaces:
trait UserRepositoryComponent {
val userRepository: UserRepository
class UserRepository {...}
}
trait UserServiceComponent {this: UserRepositoryComponent =>
val userService: UserService
class UserService {...}
}
class Context extends UserServiceComponent with UserRepositoryComponent {
val userRepository = new UserRepository
val userService = new UserService
}
However do we really need these "namespace traits" (UserServiceComponent
and UserRepositoryComponent
) if we can do the following ?
trait UserRepository {...}
trait UserService {this: UserRepository =>
...
}
class Context extends UserRepositoryImpl with UserService
So, my question is when and why we need the "namespace" trait in the Cake Pattern
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法有两个缺点:
Context
承担了太多责任,混合了UserRepository
、UserService
等的方法;userRepository
设为lazy val
,这将显着简化测试,如果您只想测试userService
(因此,不想引导整个基础设施);尽管我不推荐它,但在第一种情况下,您也可以在运行时更改注入实体(使用
var
)。There're 2 drawbacks in your approach:
Context
gets too much responsibility, mixing up methods fromUserRepository
,UserService
, etc.;userRepository
alazy val
, which will significantly simplify testing, if you want to testuserService
only (and, thus, don't want to bootstrap the entire infrastructure);Though I wouldn't recommend it, in the first case you can also change injecting entities at the runtime (using
var
s).与任何模式一样,当它使您的代码更干净/更可读/更可维护/更可测试时,您就需要它。
在这种情况下,您可能很想创建一个用于测试目的的备用上下文,替换“生产”版本中使用的部分或全部组件 - 如果通过文章中概述的模式。
正如 Vasil 指出的,这里的关注点分离是一件好事,并且几乎是蛋糕模式的全部要点。
As with any pattern, you need it when it makes your code cleaner/more readable/more maintainable/more testable.
In this case, you may well want to create an alternate context for testing purposes, substituting some or all of the components used in the "production" version - a task which is more easily achieved, and more self-documenting, if done via the pattern as outlined in the article.
As Vasil pointed out, the separation of concerns here is a Good Thing(tm), and is pretty much the entire point of the cake pattern.