Re: [心得] 控制反轉 (IoC) 與 依賴注入 (DI)

作者: pttworld (批踢踢世界)   2016-11-24 15:56:00
※ 引述《Jasonzheng (jason)》之銘言:
: 回覆 pttworld 大:
: 我已閱讀完,您於 Java 版的回文內容,也很感謝,您終於願意說清楚您的論點,那我認
: 為事情就能好好討論。
: 但為了避免誤會,想先跟您釐清一些名詞的意義,也歡迎大大們,告訴我你們的答案:
: 非常簡單的例子
: 有一個類別 Button (按鍵)
: 按一下 就可以關閉或開啟 Lamp (檯燈)
: 1. 高階模組 與 低階模組 分別為何?
高:Button
高介面:ButtonServer
低:Lamp
: 高階模組 跟 高階策略 意義一樣嘛?
: 2. 程式碼中,是高階模組「建立」低階模組,
: 還是 低階模組 「建立」高階模組?
低建立高,new Lamp();
不過精確應該是低建立了之後在高內使用。
你的原文文法是這麼設定誰建立誰的,但如果要精確的話如上。
: 3. 這有做到 IoC/DI 嘛?
NO。沒有。
沒有注入ButtonServer的程式。
: http://i.imgur.com/5M8YK6o.jpg
: http://i.imgur.com/BfvhkO1.jpg
: 執行兩次 click 的結果,當然就是
: 檯燈關閉嚕
: 檯燈打開嚕
題外話是
程式公式是對的,但是
https://en.wikipedia.org/wiki/Dependency_injection
// An example without dependency injection
public class Client {
// Internal reference to the service used by this client
private Service service;
// Constructor
Client() {
// Specify a specific implementation in the constructor instead of
using dependency injection
service = new ServiceExample();
}
// Method within this client that uses the services
public String greet() {
return "Hello " + service.getName();
}
}
Lamp原本是藏在Button裡的,但是DIP使得出現了ButtonServer,
ServerExample原本是藏在Client裡的,但是DIP使得出現了Service,
(藏在的專詞是Reference)
你會發現Service和和ServiceExample有定名上的關係。
可是Lamp和ButtonServer很難聯想到關係,反而是Button和ButtonServer容易混淆。
題外話的部分不強求,因為公式是對的。

Links booklink

Contact Us: admin [ a t ] ucptt.com