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