Re: [請益] Dependency Injection 疑問

看板PHP作者 (自宅程式猿)時間10年前 (2015/06/11 09:03), 編輯推噓2(2013)
留言15則, 3人參與, 最新討論串3/3 (看更多)
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
你上述的方法我一樣可以轉成 abstract
06/11 15:21, 3F

06/11 15:22, , 4F
像我的 sample code 說的 (new Game(new Mario))->play()
06/11 15:22, 4F

06/11 15:23, , 5F
變成 (new Mario)->play() 這樣而已
06/11 15:23, 5F

06/11 15:23, , 6F
結果是完全一樣的,這個設計準則不太可能只是語意而已吧
06/11 15:23, 6F

06/11 23:10, , 7F
如我前面所說,這個例子不是依賴的 Service/Client 關係
06/11 23:10, 7F

06/11 23:15, , 8F
Mario 就是 Game 的 subclass。若設計成 DI 的話,就可以
06/11 23:15, 8F

06/11 23:16, , 9F
在程式執行時置換新的遊戲引擎,如
06/11 23:16, 9F

06/11 23:17, , 10F
$game = new Game; $game->select(mario); $game->play();
06/11 23:17, 10F

06/11 23:18, , 11F
要存檔換 race 就像
06/11 23:18, 11F

06/11 23:19, , 12F
$game->save(); $game->select(race); $game->play();
06/11 23:19, 12F

06/11 23:21, , 13F
而 subclass 的方式稱為 template method,它一樣可以把共
06/11 23:21, 13F

06/11 23:22, , 14F
通的實作抽到上層,但使用上就不像 DI 自由,如不能在執行
06/11 23:22, 14F

06/11 23:23, , 15F
時抽換、依賴 parent class 等等。
06/11 23:23, 15F
文章代碼(AID): #1LUDvQ7_ (PHP)
文章代碼(AID): #1LUDvQ7_ (PHP)