Dependency Injection
Hai Feng Kao
1
很久很久以前
主管給我的第一個project
2
3
4
原來這就是大人的世界
後來接觸了TDD (Test Driven Design)
• Constructor 參數太多不好測試
5
6
多年之後
發現世界上有一個東西
叫做Dependency Injection
7
8
你無法預先把點點滴滴串連
起來;只有在未來回顧時,
你才會明白那些點點滴滴是
如何串在一起的。所以你得
相信,眼前你經歷的種種,
將來多少會連結在一起。
開心地到處講
但是學長卻說…
9
Dependency Injection
Hai Feng Kao
10
Dependency Injection
Hai Feng Kao
11
Why Dependency Injection?
• Testable
• Maintainability
• Loose coupling
• Collaboration
• program to an interface
12
Reference http://huan-lin.blogspot.com/2011/10/dependency-injection-1.html
Dependency Injection
• Constructor Injection
• Property Injection
• Method Injection
13
Reference http://objccn.io/issue-15-3/
An Example
• Stolen from http://objccn.io/issue-15-3/
14
15
Constructor Injection
• 構造器注入,即將某個依賴對象傳入到構造器
中 (在 Objective- C中指 designated 初始化方
法) 並存儲起來,以便在後續過程中使用
16
17
Property Injection
• 對於屬性注入,nextReminderId 的代碼看起
來和 self.userDefaults 的做法是一致的。只是
這次不是將依賴對象傳遞給初始化方法,而是
采用屬性賦值方式
18
19
Method Injection
• 如果依賴對象只在某一個方法中被使用,則可
以利用方法參數做注入
20
21
控制正轉
Not Inversion of Control
22
Example
NSUserDefault
DiskIO
創造
創造
Something
創造
控制反轉
IOC (Inversion of Control)
23
Something
NSUserDefault
DiskIO
創造
創造
Example
1. 創造Example
2. 把創造出來的
NSUserDefault餵給Example
24
IOC
Dependency
Injection
其它雜七雜八的方
法
其它雜七雜八的方法
• Extract and Override Call
• Service Locator
• Aspect-Oriented Programming
• Template Method
25
Extract and Override Call
• 用繼承來改變物件的依賴關係
26
27
28
Service Locator
• 用factory把物件創造出來
• objection (service locator for objective-c)
• https://github.com/atomicobject/objection
29
30
31
AOP (Aspect-Oriented Programming)
• 面向側面的程式設計(aspect-oriented programming,AOP
,又譯作面向方面的程式設計、觀點導向編程、剖面導向程
式設計)是電腦科學中的一個術語,指一種程式設計典範。
該典範以一種稱為側面(aspect,又譯作方面)的語言構造
為基礎,側面是一種新的模組化機制,用來描述分散在物件
、類或函式中的橫切關注點(crosscutting concern)
側面的概念源於對物件導向的程式設計的改進,但並不只限於
此,它還可以用來改進傳統的函式。與側面相關的編程概念還
包括元物件協定、主題(subject)、混入(mixin)和委託。 32
AOP
33
34
35
Template Method
• 把依賴的物件當成Template的參數傳入
• Swift only
36
37
38
Which one is better?
• My Preference
• Constructor Injection
• Template Method (Swift)
• Service Locator (Objective-C)
39
Thank You
40

不能說的Dependency injection