Thursday, March 24, 2022

[Architecture] IoC/DI

IoC,是一種 設計原則:

藉由 『分離組件 (Components) 的設置與使用』,來降低類別或模組之間的耦合度 (i.e., 解耦)。

Martin Fowler,因認為 “IoC” 的意義易使人困惑,

於 2000 年初,與多位 IoC 提倡者,給予其實作方式一個更具體的名稱

— — "Dependency Injection (依賴注入)"。

由 服務容器 (IoC 容器) 透過 “依賴注入”,給予 高階模組 所需得具體產品:


取代傳統的主動建立實例:




IoC/DI 很好的實現 好萊塢原則 (Hollywood Principle)、

依賴倒置原則 (Dependency Inversion Principle, DIP) 、 開閉原則 (Open-Closed Principle) …etc.,

是框架的必備特徵,當然也是各語言主流框架的核心 (e.g. : Spring, Laravel, .Net MVC …) 。


控制流程有 Framework 完成


callback function as a dependency of the object that it is being passed into. 

DI is the process of providing the callback (the dependency) to the object. (For example: by giving it to the object via its constructor, a method call, a setter, etc.).


翻译: callback是具体的依赖, DI是注入依赖的过程


DI是IoC的子集





IoC(I nversion o f C ontrol ): - 这是一个通用术语,以多种方式实现(事件,代理等)。

DI(D ependency I njection): - DI是IoC的子類型,通過構造函數註入,setter註入或接口註入實現


依賴注入 (Dependency Injection)


有以下三種形式:

  1. 建構元注入 (Constructor Injection)
  2. 設值方法注入 (Setter Injection)
  3. 介面注入 (Interface Injection)


class Computer implements GameInjector {

    private Game game; // 依賴 『抽象』,而非『具體』

    // 建構元注入 (Constructor Injection)
    public Computer(Game game) {
        this.game = game;
    }

    // 設值方法注入 (Setter Injection)
    public void setGame(Game game) {
        this.game = game;
    }

    // 介面注入 (Interface Injection)
    @Override
    public void injectGame(Game game) {
        this.game = game;
    }

    public void playGame() {
        if (game != null) {
            game.play();
        }
    }
}

// 遊戲注入者
// 可以規範: 任何需要 "遊戲" 的模組 都必須實做此介面
interface GameInjector{
    void injectGame(Game game);
}



可以看到程式中,沒有任何 “具體實作類別” 的名稱,
而是由 依賴注入 取得 插件實例,
高階模組,完全沒有與具體實作 耦合,
實現了 依賴倒置原則 (Dependency Inversion Principle, DIP) !


Reference:

https://www.codeproject.com/Articles/592372/Dependency-Injection-DI-vs-Inversion-of-Control-IO

https://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection

https://martinfowler.com/articles/dipInTheWild.html#YouMeanDependencyInversionRight

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能