Dependency Injection

IoC模式基本上是一个高层的概念,在 Martin Fowler 的Inversion of Control Containers and the Dependency Injection 中谈到,实现IoC有两种方式: Dependency Injection与Service Locator, Castle 所采用的是Dependency Injection 来实现 IoC,中文翻译为依赖注入,依赖注入的意义是:“保留抽象接口,让组件依赖于抽象接口,当组件要与其它实际的对象发生依赖关系时,藉过抽象接口来注入依赖的实际对象。”

看看下面这个程序:

public class BusinessObject {
privateFloppyWriterwriter=newFloppyWriter();
.

publicvoidSave(){

writer.SaveToFloppy();

}

}



BusinessObject 依赖于实际的 FloppyWriter,为了让 BusinessObject 获得重用性,不让 BusinessObject 直接依赖于实际的 FloppyWriter,而是依赖于抽象的接口:

 
 
public interface IDeviceWriter {
publicvoidSaveToDevice();
}


public class BusinessObject {
privateIDeviceWriterwriter;

publicDeviceWriter
{
Set
{
this.writer=value;
}

}


publicvoidSave(){
.
writer.SaveToDevice();
}

}


public class FloppyWriter:IDeviceWriter {
publicvoidSaveToDevice(){
.
//实现储存至Floppy的程序代码
}

}


public class UsbDiskWriter:IDeviceWriter {
publicvoidSaveToDevice(){
.
//实现储存至UsbDisk的程序代码
}

}


如果今天BusinessObject想要与UseDiskWriter对象发生依赖关系,可以这么建立: businessObject.SetDeviceWriter(new UsbDiskWriter());

由于BusinessObject依赖于抽象接口,在需要建立依赖关系时,可以通过抽象接口注入依赖的实际对象。

依赖注入在Martin Fowler的文章中谈到了三种实现方式:Interface injection、Setter injection 与 Constructor injection。并分别称其为Type 1 IoC、Type 2 IoC 与 Type 3 IoC。

上面的BusinessObject所实现的是Type 2 IoC,通过属性注入依赖关系,而Type 3 IoC,则在是构造函数上注入依赖关系,例如:

 
 
public class BusinessObject {
privateIDeviceWriterwriter;

publicBusinessObject(IDeviceWriterwriter){
this.writer=writer;
}


publicvoidSave(){
.
writer.SaveToDevice();
}

}

你可能感兴趣的:(dependency)