What is Inversion of Control?

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

    Let to say that we make some meeting in some hotel.

    Many people, many carafes of water, many plastic cups.

    When somebody want to drink, she fill cup, drink and throw cup on the floor.

    After hour or something we have a floor covered of plastic cups and water.

    Let invert control.

    The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

    and she all of time offers to guests drinking.

    When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

    Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

    And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

    Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

    meeting members will need glass of water but not piece of cake.

    Example:-

    public class MeetingMember {
    
        private GlassOfWater glassOfWater;
    
        ...
    
        public void setGlassOfWater(GlassOfWater glassOfWater){
            this.glassOfWater = glassOfWater;
        }
        //your glassOfWater object initialized and ready to use...
        //spring IoC  called setGlassOfWater method itself in order to
        //offer to meetingMember glassOfWater instance
    
    }
    

    Useful links:-

    • http://adfjsf.blogspot.in/2008/05/inversion-of-control.html
    • http://martinfowler.com/articles/injection.html
    • http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx

提交回复
热议问题