What is Inversion of Control?

前端 未结 30 3474
清歌不尽
清歌不尽 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:24

    I like this explanation: http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

    It start simple and shows code examples as well.

    The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?

    Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?

    By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.

    In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.

    Read article for further info and description of benefits such as:

    • X is not dependent on Y anymore
    • More flexible, implementation can be decided in runtime
    • Isolation of code unit, easier testing

    ...

提交回复
热议问题