IOC (Inversion of control) Basics With Example
IOC, one of the most buzzing words in IT. I will describe its clear cut meaning with example in this article.
Formal Definition: IOC is an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to traditional programming.
Before discussing further, let me give you one example,
1) Traditional Programming

You will instantiate ObjectB and ObjectC within Class A by calling constructors of B and C somewhere within Class A. That means creation of ObjectB and ObjectC depends on programming.
Sample Code
Class A{
B b;
C c;
/* See how b and c are instantiated by calling constructor of class B and C.
That means, Class A needs knowledge about B and C like
‘Which are the possible constructors of B and C?
What should be the constructor parameters?’
This is called as Tight coupling between A and B/A and C.
*/
Public A(){
b = new B();
c = new C();
}
}
2) IOC Programming

Instantiation of ObjectB and ObjectC will be done by container and will be provided to Class A directly. You can either provide created object as a Constructor Argument (Constructor Injection) or using Setter Method (Setter Injection). You need to declare this thing in Configuration File (e.g. XML)
Sample Code
Class A{
B b;
C c;
/* Look Object of class B and C will be created by Container and provided as Constructor argument.
So, Class A doesn’t need to know class B and C constructors and all.
It is loose coupling between A and B/A and C.
*/
Public A(B b, C c){
this.b = b;
this.c = c;
}
}
Conclusion:
In traditional way, object instantiation is done by YOUR PROGRAM, not CONTAINER. But with IOC pattern, it is done by CONTAINER, not YOU. That means CONTROL is just INVERSED. So, this concept is called as ‘Inversion Of Control’.!!
Benefits of IOC:
Loose coupling, reusable components and easy to configure application.
So, at the end of day, may be



<!–[endif]–>


















3 Comments
Priya
03.18.2010
Fantastic site and information on spring
Mohamad
11.24.2010
thank u so much,
please help me more for understand IOC
thanks again
mahesh
11.27.2010
Really Really one of simple and best info link on IOC. Thanks a lot “Gaurang Patel”.
Please update me any updation on spring to my mail. Thank you once again for a best info.
There are no trackbacks to display at this time.