本文介紹S.O.L.I.D原則中的介面隔離原則(Dependency Inversion Principle,縮寫為DIP)。
定義:
高層次的模組不應該依賴於低層次的模組,兩者都應該依賴於抽象介面。
抽象介面不應該依賴於細節。而細節則應該依賴於抽象介面。
High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions
解釋: 與其具體的指明物件關係,不如抽象觀念替代
例子: 假如你今天下班後到一家餐廳用餐,你先選擇吃蝦仁炒飯(具體),但服務生告訴你蝦仁炒飯已賣完。所以為了預防這種情況發生,你應該選擇其它餐點(抽象)。這樣你的晚餐選擇性就多了。

程式碼範例:
在C#範例裡,我們用Unity套件幫我用IOC容器概念實現DIP原則。
控制反轉(IoC):本名為Inversion Of Control,也就是應用程式把物件的建立和維護權交給外部容器(Unity)來實作和負責,也就是控制權轉移到外部IoC容器負責
依賴注入(DI): 本名為Dependency Injection則為實現IoC的方法。

建立介面

實作介面(牛肉麵和蝦仁炒飯)
蝦仁炒飯

牛肉麵

主控台部分

執行結果

結語:
DIP主要目的是達成loose coupling「寬鬆耦合」。試想你如果把具體類別寫死,以後如果你要做單元測試,那就要為每個具體類別各別做單元測試。如果改用DIP和unity套件,就無需如此且可增加程式碼的可維護性。