scalaにおけるimplicitによる依存注入
1029 ワード
import scala.collection.mutable
/**
* Created by xiaojun on 2015/2/17.
*/
object ScalaDemo extends App {
case class User(userId: Int, userName: String)
class UserDao {
var users = mutable.HashMap((1, User(1, "aaa")), (2, User(2, "bbb")), (3, User(3, "ccc")))
def findById(userId: Int) = users.get(userId)
def findAll() = users
def updateById(u: User) = users.update(u.userId, u)
}
implicit val userDao = new UserDao
class UserService(implicit dao: UserDao) {
def getAllUsers() = dao.findAll()
def updateUser(u: User) = dao.updateById(u)
}
// UserDao , userDao UserService
val service = new UserService
println(service.getAllUsers())
// users userid=1
service.updateUser(User(1, "AAA"))
println(service.getAllUsers())
// UserService service2, service users , userDao
val service2 = new UserService
println(service2.getAllUsers())
}