我讀過一些關於Scala的蛋糕模式的文章,基本理解它。以下是我從這篇文章複製了一些示例代碼:我可以說這個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])
}
我的問題是,是我的代碼仍然可以被視爲「依賴注入」?
- 我宣佈在
UserService
的構造 - 我與對象合併它們的依賴關係在不同的環境
但我不提供一些特質爲‘組件’。
這是Cake模式,經常使用它是所謂的「依賴注入」,它可以被看作是由Cake促進的「組件化」軟件的特例。 –