看板 PHP 關於我們 聯絡資訊
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
et282523: 推,感覺很清楚! 06/11 09:56
chan15: 我的問題好像表達不是很清楚,我的問題是差異在哪 06/11 15:20
chan15: 你上述的方法我一樣可以轉成 abstract 06/11 15:21
chan15: 像我的 sample code 說的 (new Game(new Mario))->play() 06/11 15:22
chan15: 變成 (new Mario)->play() 這樣而已 06/11 15:23
chan15: 結果是完全一樣的,這個設計準則不太可能只是語意而已吧 06/11 15:23
eight0: 如我前面所說,這個例子不是依賴的 Service/Client 關係 06/11 23:10
eight0: Mario 就是 Game 的 subclass。若設計成 DI 的話,就可以 06/11 23:15
eight0: 在程式執行時置換新的遊戲引擎,如 06/11 23:16
eight0: $game = new Game; $game->select(mario); $game->play(); 06/11 23:17
eight0: 要存檔換 race 就像 06/11 23:18
eight0: $game->save(); $game->select(race); $game->play(); 06/11 23:19
eight0: 而 subclass 的方式稱為 template method,它一樣可以把共 06/11 23:21
eight0: 通的實作抽到上層,但使用上就不像 DI 自由,如不能在執行 06/11 23:22
eight0: 時抽換、依賴 parent class 等等。 06/11 23:23