What is Inversion of Control?

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

    Inversion of Control is what you get when your program callbacks, e.g. like a gui program.

    For example, in an old school menu, you might have:

    print "enter your name"
    read name
    print "enter your address"
    read address
    etc...
    store in database
    

    thereby controlling the flow of user interaction.

    In a GUI program or somesuch, instead we say:

    when the user types in field a, store it in NAME
    when the user types in field b, store it in ADDRESS
    when the user clicks the save button, call StoreInDatabase
    

    So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.

    Basically, anything with an event loop, callbacks, or execute triggers falls into this category.

提交回复
热议问题