I、接口注入型
II、Setter注入型
III、构造注入型
其中IOC TypeI和II之间很容易混淆,笔者在学习时也有点乱。因此特写此文以作备忘。下面转入正文:
在下面的代码示例中主要包含class A 、interface IB 、class getInstanceOfB、interface IGetServiceImpl四个类或接口。
interface IB
{
void exe();
}
interface IGetServiceImpl
{
void getInstance(String instanceType);
}
IOC typeI:
class A
{
IB inst;
void execute()
{
String result = this.inst.exe();
System.out.println("the result is:" + result);
}
void getInstanceOfB(IB instance)
{
this.inst = instance;
}
}
或者
class A implents IGetServiceImpl
{
IB inst;
void execute()
{
String result = this.inst.exe();
System.out.println("the result is:" + result);
}
void getInstanceOfB(IGetServiceImpl getSerImpl)
{
this.inst = getSerImpl.getInstance("IB");
}
}
这种情况出现于Avalon Framework。一个组件实现了IGetServiceImpl接口,就必须实现getInstanceOfB方法,并传入一个IGetServiceImpl 对象示例。其中会含有需要的其它组件。只需要在getInstanceOfB方法中初始化需要的IB对象
IOC typeII:
class A
{
IB inst;
void execute()
{
String result = this.inst.exe();
System.out.println("the result is:" + result);
}
void setInstanceOfIB(IB instance)
{
this.inst = instance;
}
}
IOC类型I和类型II之间特容易搞混的就是,类型II不也是通过接口注入了一个对象吗?
但实际上这二者是有区别的,尤其是通过上述代码中的IOC类型I的第二个示例代码即可看出区别,即
“IOC类型I在注入对象实例时,不是直接注入,而是稍微绕了一个弯,通过一个类似于中介的接口进行注入,而IOC类型II是直接将需要的对象注入到程序中。”