您的位置:首页 > 其它

控制反转(IOC)Inversion of Control或依赖注入(DI)Dependency Injection

2007-03-27 11:24 741 查看
控制反转(IOCInversion of Control或依赖注入(DIDependency Injection.

参考:http://blog.exadel.com/?p=6
Getting to Absolute Zero: Injection of Control and JavaServer Faces http://www.martinfowler.com/articles/injection.html The idea is simple: separate(分离或解耦) dependency(依赖关系) management from the main business code



Figure 1: Injection of Control(去除或减弱)the dependency(依赖关系) between SessionFactoryImpl(即在Service类中注入了一个[b]SessionFactory接口).[/b] and Service. So, we add a special class called Assembler that “injects” the dependency into Service using plain setter calls

Let’s look more closely at this figure. Here we have a Service that needs a SessionFactory to perform queries into a database. The goal is to remove
Spring can provide you with a SessionFactory implementation for many different persistence frameworks like Hibernate.(spring能提供不同SessionFactory接口的实现。)

下面仅用JSF的控制反转(IOC)Inversion of Control进行说明。

SessionFactory and Service are assembled together in the faces-config.xml configuration



Figure 2: Session Factory Interface



Figure 3: Session Factory Implementation



Figure 4: Service Implementation



Figure 5: faces-config.xml File for JSF Configuration



[align=left]Ioc模式(Dependency Injection模式)有三种:[/align]
[align=left]第一种类型[/align]
[align=left]从JNDI或ServiceManager等获得被调用者,这里类似ServiceLocator模式。[/align]
[align=left]1. EJB/J2EE
2. Avalon(Apache的一个复杂使用不多的项目)[/align]
[align=left]第二种类型[/align]
[align=left]使用JavaBeans的setter方法[/align]
[align=left]1. Spring Framework,
2. WebWork/XWork[/align]
[align=left]第三种类型[/align]
[align=left]在构造方法中实现依赖[/align]
[align=left]1. PicoContainer,
2. HiveMind[/align]
依赖注入的形式主要有三种,我分别将它们叫做构造子注入(Constructor Injection)、设值方法注入(Setter Injection)和接口注入(Interface Injection)。这三种注入形式分别就是 type 1 IoC(接口注入)、type 2 IoC(设值方法注入)和 type 3 IoC(构造子注入)。

Dependency Injection模式并不是打破这层依赖关系的唯一手段,另一种方法是使用Service Locator模式
我们面临Service Locator和 Dependency Injection之间的选择。应该注意,尽管我们前面那个简单的例子不足以表现出来,实际上这两个模式都提供了基本的解耦合能力——无论使用哪个模式,应用程序代码都不依赖于服务接口的具体实现。两者之间最重要的区别在于:这个“具体实现”以什么方式提供给应用程序代码。使用 Service Locator 模式时,应用程序代码直接向服务定位器发送一个消息,明确要求服务的实现;使用 Dependency Injection模式时,应用程序代码不发出显式的请求,服务的实现自然会出现在应用程序代码中,这也就是所谓“控制反转”.
一个关键的区别在于:使用 Service Locator 模式时,服务的使用者必须依赖于服务定位器。定位器可以隐藏使用者对服务具体实现的依赖,但你必须首先看到定位器本身。所以,问题的答案就很明朗了:选择 Service Locator还是 Dependency Injection,取决于“对定位器的依赖”是否会给你带来麻烦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: