我可以说这个scala代码是依赖注入的吗?

时间:2014-06-19 14:46:55

标签: scala dependency-injection cake-pattern

我已经阅读了一些关于Scala蛋糕模式的文章,基本上理解它。以下是我从本文中复制的一些示例代码:

组件:

case class User(username:String, password: String)

trait UserRepositoryComponent {
  val userRepository: UserRepository

  class UserRepository {
    def authenticate(user: User): User = { 
      println("authenticating user: " + user)
      user
     }
    def create(user: User) = println("creating user: " + user)
    def delete(user: User) = println("deleting user: " + user)
  }
}


trait UserServiceComponent { this: UserRepositoryComponent =>
  val userService: UserService
  class UserService {
    def authenticate(username: String, password: String): User = 
      userRepository.authenticate(User(username, password))  

    def create(username: String, password: String) = 
      userRepository.create(new User(username, password))

    def delete(user: User) = 
      userRepository.delete(user)

  }
}

组合它们的对象:

object ComponentRegistry extends 
  UserServiceComponent with 
  UserRepositoryComponent {
  val userRepository = new UserRepository
  val userService = new UserService
}

object TestingComponentRegistry extends 
  UserServiceComponent with 
  UserRepositoryComponent {
  val userRepository = mock[UserRepository]
  val userService = mock[UserService]
}

如果我在一个简单的项目中,我想让它变得更简单。代码如下:

case class User(username:String, password: String)

class UserRepository {
  def authenticate(user: User): User = { 
    println("authenticating user: " + user)
    user
   }
  def create(user: User) = println("creating user: " + user)
  def delete(user: User) = println("deleting user: " + user)
}

class UserService(userRepository: UserRepository) {
  def authenticate(username: String, password: String): User = 
    userRepository.authenticate(User(username, password))  

  def create(username: String, password: String) = 
    userRepository.create(new User(username, password))

  def delete(user: User) = 
    userRepository.delete(user)

}

结合它们:

object Application {
  val userService = new UserService(new UserRepository)
}

object Test {
  val userService = new UserService(mock[UserRepository]) 
}

我的问题是,我的代码仍然可以被视为"依赖注入"?

  1. 我在UserService的构造函数
  2. 中声明了依赖项
  3. 我将它们与不同环境中的对象结合起来
  4. 但我并没有提供一些特质作为"组件"。

1 个答案:

答案 0 :(得分:3)

是的,您的代码是"依赖注入":UserService接收它应该用作构造函数参数的组件,而不是在{{1}中直接实例化UserRepository }}

恕我直言,您的代码正好什么DI应该是90 +%的时间。不需要一些"幻想"像Spring或Guice这样的框架,不需要一些" fancy"设计模式,如蛋糕模式,只需在构造函数中注入依赖项。完成,清洁,易于测试,易于更换不同的实现(*)。

(*):请注意,在您的示例UserService中实现此目的应该是一个特征而不是一个类。