What is Inversion of Control?

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

    I've read a lot of answers for this but if someone is still confused and needs a plus ultra "laymans term" to explain IoC here is my take:

    Imagine a parent and child talking to each other.

    Without IoC:

    *Parent: You can only speak when I ask you questions and you can only act when I give you permission.

    Parent: This means, you can't ask me if you can eat, play, go to the bathroom or even sleep if I don't ask you.

    Parent: Do you want to eat?

    Child: No.

    Parent: Okay, I'll be back. Wait for me.

    Child: (Wants to play but since there's no question from the parent, the child can't do anything).

    After 1 hour...

    Parent: I'm back. Do you want to play?

    Child: Yes.

    Parent: Permission granted.

    Child: (finally is able to play).

    This simple scenario explains the control is centered to the parent. The child's freedom is restricted and highly depends on the parent's question. The child can ONLY speak when asked to speak, and can ONLY act when granted permission.

    With IoC:

    The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted! The child is now free to ask questions anytime and though there is still dependency with the parent regarding permissions, he is not dependent in the means of speaking/asking questions.

    In a technological way of explaining, this is very similar to console/shell/cmd vs GUI interaction. (Which is answer of Mark Harrison above no.2 top answer). In console, you are dependent on the what is being asked/displayed to you and you can't jump to other menus and features without answering it's question first; following a strict sequential flow. (programmatically this is like a method/function loop). However with GUI, the menus and features are laid out and the user can select whatever it needs thus having more control and being less restricted. (programmatically, menus have callback when selected and an action takes place).

提交回复
热议问题