关于蛋糕模式的问题

Mic*_*ael 3 scala traits

Cake Pattern 文章建议使用性状命名空间:

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  
} 
Run Code Online (Sandbox Code Playgroud)

但是UserServiceComponent,UserRepositoryComponent如果我们可以执行以下操作,我们是否真的需要这些"命名空间特征"(和)?

trait UserRepository {...}

trait UserService {this: UserRepository => 
  ...
}

class Context extends UserRepositoryImpl with UserService
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是我们何时以及为什么需要"命名空间"特征Cake Pattern.

Vas*_*iuk 5

您的方法有两个缺点:

  1. Context得到了太多的责任,混合了来自法UserRepository,UserService等等;
  2. 在第一个片段中,您可以控制初始化的顺序,或者为某些组件延迟它 - 例如,如果您只想进行测试(并且因此不想引导,您可以制作userRepository一个lazy val,这将显着简化测试)userService整个基础设施);

虽然我不推荐它,但在第一种情况下,您还可以在运行时更改注入实体(使用vars).