A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
高層模塊不應依賴低層模塊,二者皆應依賴抽象。
B. Abstractions should not depend on details. Details should depend on abstractions.
抽象不應依賴細節,細節應依賴抽象。
// 傳統分層:高層 → 低層 (緊耦合)
class UserController { // 高層:業務邏輯
constructor() {
this.db = new MySQLDB(); // 直接依賴具體 MySQL 實現
}
}
// DIP 重構:高層定義接口,低層實現接口
interface UserRepository { // 抽象 (由高層定義)
findById(id);
save(user);
}
class MySQLUserRepo implements UserRepository { ... } // 低層實現
class MongoUserRepo implements UserRepository { ... } // 另一實現
class UserController {
constructor(private repo: UserRepository) {} // 依賴抽象
// 運行時注入具體實現
}
JS 無接口關鍵字,但通過鴨子類型、依賴注入 (DI)、工廠/容器 實現同樣效果。
// 1. 定義抽象接口 (文檔/約定)
/**
* @interface MapProvider
* @method showMap(element, lat, lng, icon, title)
* @method updateMap(lat, lng)
*/
// 2. 高層組件僅依賴接口
$.fn.trackMap = function(options) {
var opts = $.extend({}, defaults, options);
// 調用抽象接口方法
opts.provider.showMap(this[0], opts.lat, opts.lng, opts.icon, opts.title);
opts.feed.update(function(lat, lng) {
opts.provider.updateMap(lat, lng); // 同樣調用抽象方法
});
return this;
};
// 3. 具體實現:Google Maps 適配器
trackMap.googleMapsProvider = (function() {
var map, marker;
return {
showMap: function(el, lat, lng, icon, title) {
map = new google.maps.Map(el, { center: {lat, lng}, zoom: 12 });
marker = new google.maps.Marker({ position: {lat, lng}, map, icon, title });
},
updateMap: function(lat, lng) {
var pos = new google.maps.LatLng(lat, lng);
marker.setPosition(pos);
map.setCenter(pos);
}
};
})();
// 4. 使用時注入具體實現
$("#map").trackMap({
lat: 35.04, lng: -89.98,
provider: trackMap.googleMapsProvider, // 注入
feed: locationFeed
});
| 概念 | 關注點 | 關係 |
|---|---|---|
| DIP | 架構層面:高層不依賴低層,雙方依賴抽象 | 原則 |
| DI | 實現層面:依賴如何被提供給組件 (構造器注入、屬性注入、方法注入) | 模式 (IOC 容器實現) |
| IOC 容器 | 框架:自動解析依賴圖、生命周期管理、配置綁定 | 工具 |
DIP 是架構目標,DI 是實現手段,IOC 容器是自動化工具。JS 中常手動 DI 或用簡易容器 (如 InversifyJS、Awilix)。
class Container {
constructor() { this.bindings = new Map(); }
bind(token, factory) { this.bindings.set(token, factory); }
get(token) {
if (!this.bindings.has(token)) throw new Error(`No binding for ${token}`);
return this.bindings.get(token)(this); // 傳遞 container 自身支持嵌套解析
}
}
const container = new Container();
container.bind('UserRepository', c => new MySQLUserRepo(c.get('DB')));
container.bind('UserService', c => new UserService(c.get('UserRepository')));
const userService = container.get('UserService');