Inversion Control, also known as Dependency Injection, is a concept that separates the dependency between objects which makes it easy for testing classes, and easy to replace different object without affecting the client code.
For example:
public class B
{
public void foo()
{
// do something
}
}
public class A
{
B obj;
public A()
{
// Here object A create an object B. Therefore object A depends on object B.
obj = new B();
}
public void doSomething()
{
obj.foo();
}
}
The example above shows objects A and B are tightly couple since object A is aware of how to create object B.
======================================
Here is an example version of how to use the Inversion Control:
public interface IFoo
{
public void foo();
}
public class B implement IFoo
{
public void foo()
{
// provide implementation here
}
}
public class A
{
private IFoo obj;
public void setFoo( IFoo foo )
{
obj = foo;
}
public void doSomething()
{
obj.foo();
}
}
If you look at how Class A is defined, it is no longer responsible for creating an object B, instead it provides an method setFoo() to allow any object that implements IFoo interface to be injected by invoking this method. Injection an object into another is usually done by a container via configuraion file. This is actually how Spring framework actually does.
Hope this help.
|