What is Inversion of Control?

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

    I shall write down my simple understanding of this two terms:

    For quick understanding just read examples*
    

    Dependency Injection(DI):
    Dependency injection generally means passing an object on which method depends, as a parameter to a method, rather than having the method create the dependent object.
    What it means in practice is that the method does not depends directly on a particular implementation; any implementation that meets the requirements can be passed as a parameter.

    With this objects tell thier dependencies. And spring makes it available.
    This leads to loosely coupled application development.

    Quick Example:EMPLOYEE OBJECT WHEN CREATED,
                  IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
       (if address is defines as dependency by Employee object)
    

    Inversion of Control(IoC) Container:
    This is common characteristic of frameworks, IOC manages java objects
    – from instantiation to destruction through its BeanFactory.
    -Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.

    QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it.

    By implementing Inversion of Control, a software/object consumer get more controls/options over the software/objects, instead of being controlled or having less options.

    Inversion of control as a design guideline serves the following purposes:

    There is a decoupling of the execution of a certain task from implementation.
    Every module can focus on what it is designed for.
    Modules make no assumptions about what other systems do but rely on their contracts.
    Replacing modules has no side effect on other modules
    I will keep things abstract here, You can visit following links for detail understanding of the topic.
    A good read with example

    Detailed explanation

提交回复
热议问题