Re: [請益] Dependency Injection 疑問
Dependency Injection,指的是讓 Dependency 能在 runtime 改變,
而不影響 client 本身的實作。
而這個例子,Animal 跟 Bird 本身就沒有依賴關係,沒有
Dependency,自然沒有 DI 的感覺。
若以電腦和影印機、螢幕來舉例,電腦需要用輸出裝置才能輸出訊息︰
class Computer
{
public $output;
public function use($something) {
$this->output = $something;
}
public function say_hi() {
$this->output("Hi I am computer!");
}
}
function printer($src_string) {
// print $src_string to printer...
}
function screen($src_string) {
// put $src_string on screen...
}
那麼在使用時就可以很隨易的使用不同裝置︰
$computer = new Computer
$computer->use(printer);
$computer->say_hi();
$computer->use(screen);
$computer->say_hi();
今天突然改版,不用印表機也不用螢幕,改用沙畫。
那你只要建立一個沙畫的 service,要用時 inject 進 computer 就行了︰
function draw_on_sand($src_string) {
// draw string on sand...
}
$computer->use(draw_on_sand);
$computer->say_hi();
又或者你只是要 debug,想把電腦的輸出印到自己的螢幕上︰
funcion print($src_string) {
echo $src_string;
}
$computer->use(print);
$computer->say_hi();
到這邊應該看得出來,Dependency Injection 的好處就是,Client 完全
不用知道 $this->output 是什麼玩意,只要把字串送給它就好。
引述前一篇 banjmin
> 關係被"介面"decoupling了
> 也就是"針對介面寫程式,不要針對實作寫程式"的OO守則
--
(* ̄▽ ̄)/‧★*"`'*-.,_,.-*'`"*-.,_☆,.-*`
http://i.imgur.com/oAd97.png

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.225.50.176
※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1433984602.A.1FF.html
推
06/11 09:56, , 1F
06/11 09:56, 1F
推
06/11 15:20, , 2F
06/11 15:20, 2F
→
06/11 15:21, , 3F
06/11 15:21, 3F
→
06/11 15:22, , 4F
06/11 15:22, 4F
→
06/11 15:23, , 5F
06/11 15:23, 5F
→
06/11 15:23, , 6F
06/11 15:23, 6F
→
06/11 23:10, , 7F
06/11 23:10, 7F
→
06/11 23:15, , 8F
06/11 23:15, 8F
→
06/11 23:16, , 9F
06/11 23:16, 9F
→
06/11 23:17, , 10F
06/11 23:17, 10F
→
06/11 23:18, , 11F
06/11 23:18, 11F
→
06/11 23:19, , 12F
06/11 23:19, 12F
→
06/11 23:21, , 13F
06/11 23:21, 13F
→
06/11 23:22, , 14F
06/11 23:22, 14F
→
06/11 23:23, , 15F
06/11 23:23, 15F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
PHP 近期熱門文章
PTT數位生活區 即時熱門文章