Kotlin Advent Calendar 2013 10æ¥ç®ã®ã¨ã³ããªã§ãã
ä¾åæ§æ³¨å ¥ããã
ã¿ã¤ãã«ã®éãä»åã¯Kotlinã§DIã«ææ¦ãDIã³ã³ãã使ããã§ãªãç´ ã®Kotlinã§ãã£ã¦ã¿ããé£ãããã¨ããããã¨ãã¦ããã®ã§ã¯ãªãã責任å¤ã®å¦çãå¥ã®ãªãã¸ã§ã¯ãã«å§è²ãã¦ã¦ããããã¹ããããæããããã ãã
ã¾ãã¯æºåã
data class Employee( val firstName: String, val lastName: String )
ãµã³ãã«ã§ãããã¡ãªEmployee
ã¯ã©ã¹ãdata
ã¢ããã¼ã·ã§ã³ã«ã¤ãã¦ã¯ãã¡ãã®ã¨ã³ããªãåç
§ã
trait EmployeeRepository { fun save(employee: Employee): Employee }
ã§ã次ã«DAOçãªãã¬ã¤ããå®ç¾©ã
ããã§createEmployee
ã¡ã½ãããæã£ãEmployeeService
ã¯ã©ã¹ãä½ãããããã®ã¯ã©ã¹ã¯EmployeeRepository#save
ã使ããJavaã ã£ããEmployeeService
ã®ã³ã³ã¹ãã©ã¯ã¿ã§EmployeeRepository
ã®ã¤ã³ã¹ã¿ã³ã¹ãåãåã£ã¦ãã£ã¼ã«ãã«ä¿æããæãã«ãªãã¨æããKotlinã¯ã¡ãã£ã¨éãã
class EmployeeService(employeeRepos: EmployeeRepository) : EmployeeRepository by employeeRepos { fun createEmployee(firstName: String, lastName: String): Employee { return save(Employee(firstName, lastName)) } }
1è¡ç®ã®: EmployeeRepository by employeeRepos
ã«æ³¨ç®ãããã«ããã¯ã©ã¹ã¯EmployeeRepository
ã®ãµãã¿ã¤ãã«ãªãããã®ã¡ã½ããã¸ã®ã¢ã¯ã»ã¹ã¯ã³ã³ã¹ãã©ã¯ã¿ã§åãåã£ãEmployeeRepository
ã¤ã³ã¹ã¿ã³ã¹ã¸èªåçã«å§è²ããããå¾®å¦ãªéãã ãã©ãemplyoeeRepos.save
ã¨ããè¨è¿°ã§ã¯ãªãåã«save
ã¨ãã¦ã¡ã½ãããå¼ã³åºãã¦ãããä½è¨ãªããããã£ãæã¤å¿
è¦ããªããªãã
å®éã«åããã¦ã¿ããEmployeeRepository
ã®å®è£
ã¨ãã¦æ¬¡ã®ã¯ã©ã¹ï¼ã¨ããããªãã¸ã§ã¯ãï¼ãå®ç¾©ããã
object DummyEmployeeRepository: EmployeeRepository { override fun save(employee: Employee): Employee { println("saved: " + employee) return employee } }
EmployeeService
ã¸ä¾åæ§ã注å
¥ãã¦å®éã«ä½¿ãã
fun main(args: Array<String>) { val employeeService = EmployeeService(DummyEmployeeRepository) employeeService.createEmployee("Taro", "Nagasawa") }
æå¾
éãsaved: Employee(firstName=Taro, lastName=Nagasawa)
ã¨åºåãããã¯ãã
æå¾ã«ããã£ããDIã§ããããã«ãªã£ããã§ç°¡åãªãã¹ããæ¸ãã
import org.junit.Test as test import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.times class EmployeeServiceTest { test fun æå®ãããååã®å¾æ¥å¡ãæ°ãã«çæãä¿åãããã¨() { val employeeRepos = mock(javaClass<EmployeeRepository>())!! EmployeeService(employeeRepos).createEmployee("Taro", "Nagasawa") verify(employeeRepos, times(1))!!.save(Employee("Taro", "Nagasawa")) } }
ãã¾ã
@ngsw_taro 太éãããDIããªãããã ã®ã¹ãã©ãã¸ã¼ãã¿ã¼ã³ãï¼
— è°·æ¬ å¿.do (@cero_t) 2013, 12æ 10
@ngsw_taro ã¤ã³ã¹ã¿ã³ã¹ã®çæï¼ã©ã¤ããµã¤ã¯ã«ç®¡çãå«ãï¼ã®è²¬åãæã¤ãDIã³ã³ãããããã¦ãã¹ãã©ãã¸ã¼ãã¿ã¼ã³ãªã©ãå®ç¾ãã¦ãã®ããDIã
— è°·æ¬ å¿.do (@cero_t) 2013, 12æ 10
ãã¿ã¾ãããé£ããªã¿ã¤ãã«ã«ãªã£ã¦ãã¾ã£ããã
ã¨æã£ãããããªãã¤ã¼ããããã ãã¾ããã
@ngsw_taro DI ã¨è¨ã£ã¦ããã¨æãã¾ããDI ã®ä¸»ç¼ã¯å¤ããå®è£
ã渡ããã¨ã§ IoC ãå®ç¾ãããã¨ãStrategy ã¯è¤æ°ã®å®è£
ãåãæ¿ãããã¨ã§ãå¿
ãããå¤ããå®è£
ã渡ãå¿
è¦ã¯ãªãã¯ãã
— shuhei (@7to3) 2013, 12æ 10