What is the dependency inversion principle and why is it important?

前端 未结 15 1095
别那么骄傲
别那么骄傲 2020-11-28 00:06

What is the dependency inversion principle and why is it important?

15条回答
  •  难免孤独
    2020-11-28 00:52

    Inversion of control (IoC) is a design pattern where an object gets handed its dependency by an outside framework, rather than asking a framework for its dependency.

    Pseudocode example using traditional lookup:

    class Service {
        Database database;
        init() {
            database = FrameworkSingleton.getService("database");
        }
    }
    

    Similar code using IoC:

    class Service {
        Database database;
        init(database) {
            this.database = database;
        }
    }
    

    The benefits of IoC are:

    • You have no dependency on a central framework, so this can be changed if desired.
    • Since objects are created by injection, preferably using interfaces, it's easy to create unit tests that replace dependencies with mock versions.
    • Decoupling off code.

提交回复
热议问题