## 依賴倒置原則
### 理解概念
含義:依賴倒置原則(Dependence Inversion Principle)是程序要依賴于抽象接口,不要依賴于具體實現。簡單的說就是要求對抽象進行編程,不要對實現進行編程,這樣就降低了客戶與實現模塊間的耦合。(來自百度百科)
關鍵:
高層模塊不應該依賴低層模塊,兩者都應該依賴其抽象
抽象不應該依賴細節
細節應該依賴抽象
目的:避免需求變化導致過多的維護工作
解釋:簡單來說就是程序要依賴于抽象接口,不要依賴于具體實現。要求對抽象進行編程,不要對實現進行編程。
~~~js
const test = {
getValue() {
return 1;
}
};
const other = {
getVal() {
return 10;
}
};
class SimpleMath {
calc(obj) {
console.log(obj.getValue() + 100);
}
};
const s = new SimpleMath();
s.calc(test); // 101
s.calc(other); // 錯誤
~~~
這個錯誤是顯而易見的, other底層類并不具備getValue方法, 所以報錯, 我們當然可以修改other讓其具備getValue, 可這樣難保其他類似的情況, 這里有一個問題, SimpleMath類實例的calc方法與底層對象產生了一個強耦合, 必須具備getValue方法的對象才能傳入calc方法, 這就違背了依賴倒置原則的高層模塊不依賴底層模塊, 所以更好的做法是消除該依賴
~~~js
const test = {
getValue() {
return 1;
}
};
const other = {
getVal() {
return 10;
}
};
class SimpleMath {
calc(getValue) {
console.log(getValue() + 100);
}
};
const s = new SimpleMath();
s.calc(test.getValue); // 101
s.calc(other.getVal); // 110
~~~
舉個栗子:
現有一個人類,人類有一個讀書的接口,因為是讀書,所以要依賴一個書類的輸出書內容的方法。這就違反了依賴倒置原則,因為你此時人類是高層模塊,書是低層模塊,高層模塊人類依賴了低層模塊書類。此時如果要讓人類去讀報紙,原有的讀書方法很難做到。
解決:
~~~
// 閱讀類
class Reader{
constructor(content) {
this.content = content
}
// 獲取內容的抽象方法
outPutContent(){
throw "Abstract methods require concrete implementation";
}
}
// 書類
class Book extends Reader{
constructor(content) {
super(content)
}
// 獲取內容的抽象方法的實現
outPutContent(){
console.log(`書的內容是${this.content}`)
}
}
// 報紙類
class NewsPaper extends Reader{
constructor(content) {
super(content)
}
// 獲取內容的抽象方法的實現
outPutContent(){
console.log(`報紙的內容是${this.content}`)
}
}
// 人類
class People{
constructor(name) {
this.name = name
}
// 讀抽象方法的具體實現
reader(what){
console.log(`${this.name}讀的`,what.outPutContent())
}
}
let xiaoMing = new People('小明')
let xiaoHong = new People('小紅')
let anTuSheng = new Book('安徒生故事')
let wanBao = new NewsPaper('今日晚報')
xiaoMing.reader(anTuSheng);// 書的內容是安徒生故事 小明讀的
xiaoMing.reader(wanBao);// 報紙的內容是今日晚報 小明讀的
xiaoHong.reader(anTuSheng);// 書的內容是安徒生故事 小紅讀的
xiaoHong.reader(wanBao);// 報紙的內容是今日晚報 小紅讀的
~~~
以上就實現了實現了依賴倒轉原則。
- 視覺規范
- 色彩
- 文字
- 偏移
- 圖標
- 列表組件
- 表單組件
- 詳情組件
- 其他組件
- 研發規范
- 編碼規范
- 函數式編程
- 純函數
- 柯里化
- 函數組合
- 函子
- 面向對象編程
- 設計原則
- 單一職責原則
- 里氏替換原則
- 依賴倒置原則
- 接口隔離原則
- 開閉原則
- 迪米特原則
- 組合復用原則
- 設計模式
- 創建型模式
- 工廠模式
- 簡單工廠
- 工廠方法
- 抽象工廠
- 單例模式
- 建造者模式
- 原型模式
- 結構型模式
- 適配器模式
- 橋接模式
- 過濾器模式
- 組合模式
- 裝飾器模式
- 外觀模式
- 享元模式
- 代理模式
- 行為型模式
- 責任鏈模式
- 命令模式
- 解釋器模式
- 迭代器模式
- 中介者模式
- 備忘錄模式
- 觀察者模式
- 狀態模式
- 策略模式
- 模板模式
- 訪問者模式
- 組件設計規范
- 組件文檔編寫規范
- 版本管理規范