7.12 其他面向对象设计原则3: 依赖倒置原则DIP
其他面向對象設計原則3: 依賴倒置原則DIP
? The Dependency Inversion Principle
7.1 依賴倒置原則DIP
The Dependency Inversion Principle
I. 高層模塊不應當依賴低層模塊 ,兩者都依賴抽象
High-level modules should not depend on low-level modules,Both should depend on abstractions
II.抽象不能依賴細節,細節應當依賴抽象
Abstractions should not depend on details, Details should depend on abstractions R. Martin, 1996
? 引導
? 繼承層次關系中,基類不應當知道任何子類
A base class in an inheritance hierarchy should not know any of its subclasses
? 不能依賴一個有詳細實現的模塊,而這個模塊本身也應當依賴抽象
Modules with detailed implementations are not depended upon, but depend themselves upon abstractions
? OCP宣揚了目標,DIP宣揚了機制
OCP states the goal; DIP states the mechanism
7.2 為什么依賴倒置原則DIP ?
? 傳統的面向過程的程序設計,以功能劃分系統
? 高層模塊是業務/應用規則 High level modules: business/application rules
? 低層模塊是對這些規則的實現 Low level modules: implementation of the business rules
? 高層模塊完全依賴調用低層模塊提供的功能來完成自己的功能
High level modules complete their functionality by calling/invoking the low level implementation provided by the low level modules
? 因此,高層依賴底層 High level depends on the lower level
7.2 為什么依賴倒置原則DIP ?
比較:過程化程序與 面向對象架構
過程化程序架構
面向對象系統架構 Object-Oriented Architecture
7.3 依賴倒置原則的啟發1
? 使用繼承,避免類之間的直接綁定 Use inheritance to avoid direct bindings to classes:
面向接口設計,而不是面向實現設計 Design to an interface, not an implementation!
? 為什么面向接口設計 Design to an Interface
? 因為
? 抽象類/接口修改的概率偏低 tend to change much less frequently
? 抽象概念容納的范圍廣,易于擴展/修改 abstractions are ‘hinge points’ where it is easier to extend/modify
? 不應當修改代表抽象的類/接口,符合OCP原則 shouldn’t have to modify classes/interfaces that represent the abstraction (OCP)
? 舉例:中央的政策不能輕易修改,而鄉鎮的政策,錯了馬上改
? 例外情況 Exceptions
? 有些類非常成熟、穩定 Some classes are very unlikely to change
? 插入抽象層,好處不多了,例如 String class,這里就可以直接使用具體類
? 此時,不考慮依賴倒置的問題了
避免傳遞性依賴 Avoid Transitive Dependencies
? 使用繼承機制,消除傳遞性依賴
? 如果對自己設計的類找不到一個滿意的解決方案,嘗試把職責委 派其他一個或者多個類
If you cannot find a satisfactory solution for the class you are designing, try delegating responsibility to one or more classes
每當有疑慮時,增加一個間接層 When in doubt, add a level of indirection
轉載于:https://www.cnblogs.com/mayZhou/p/10550064.html
總結
以上是生活随笔為你收集整理的7.12 其他面向对象设计原则3: 依赖倒置原则DIP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux系统开发之路-中
- 下一篇: 减脂每天晚上只吃全麦面包可以吗