What is Inversion of Control?

前端 未结 30 2803
清歌不尽
清歌不尽 2020-11-22 00:13

Inversion of Control (IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. Which problem does it solve?
  3. When is it appropria
30条回答
  •  有刺的猬
    2020-11-22 00:37

    What is Inversion of Control?

    If you follow these simple two steps, you have done inversion of control:

    1. Separate what-to-do part from when-to-do part.
    2. Ensure that when part knows as little as possible about what part; and vice versa.

    There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.

    --

    The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!

    --

    Examples

    • Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)
    • Dependency Injection. Code that constructs a dependency (what-to-do part) -- instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).
    • Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)
    • xUnit fixture. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
    • Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part
    • DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)

提交回复
热议问题