I've read some articles about Scala's cake pattern, basically understood it. Following is some sample code I copied from this article:
Components:
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)
}
}
Objects to combine them:
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]
}
I want to make it simpler if I'm in a simple project. The code will look like:
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)
}
Combine them:
object Application {
val userService = new UserService(new UserRepository)
}
object Test {
val userService = new UserService(mock[UserRepository])
}
My question is, is my code can still be treated as "Dependency injected"?
- I declared the dependencies in the
UserService
's constructor - I combine them with objects in different environments
But I don't provide some trait as "Components".