IoC 主要实现策略
维基百科(https://en.wikipedia.org/wiki/Inversion_of_control)
Implementation techniques 小节的定义:
“In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
面向对象编程中, 有以下几种IoC的基础实现策略:
Using a service locator pattern
服务定位模式(Service Locator), 这种模式是 Java EE 里定义的, 通常通过 JNDI 这种技术来获取 Java EE 的组件, 比如 EJB组件, DataSource等
Using dependency injection, for example
依赖注入(DI), 比如下面的例子:
实际上不仅在SpringFramework, 在 EJB 3.0 之后也有相关的实现
Constructor injection
构造器注入
Parameter injection
参数注入
Setter injection
Setter注入
Interface injection
接口注入
Using a contextualized lookup
上下文中的依赖查询, 这是另一种技术实现了, 比如 Java Beans 里有一个通用的上下文, 叫做 beancontext, 里面既可以传输Bean, 也可以管理Bean的层次性. spring的很多实现都是来自于这方面的灵感.
Using template method design pattern
模板方法的设计模式, 比如spring里面的 jdbcTemplate, 里面提供了一个 callback的回调方式, 我们不需要关心 callBack 从哪里来, 只需要用, 这也是 控制反转 的一个体现.
Using strategy design pattern
策略模式, 不太好举例.
《Expert One-on-One™ J2EE™ Development without EJB™》提到的主要实现策略:
这是本书, 由spring的两名作者编写, 其思想会极大影响我们对spring的看法. 主要思想就是开发J2EE程序是否可以脱离EJB, 认为 EJB 是不重要的, 重要的是其中的思想.
来自“Chapter 6. Lightweight Containers and Inversion of Control
“IoC is a broad concept that can be implemented in different ways. There are two main types:
IoC可以有不同的实现方式, 其中有两种主要的策略:
Dependency Lookup:
The container provides callbacks to components, and a lookup context. This is the EJB and Apache Avalon approach. It leaves the onus on each component to use container APIs to look up resources and collaborators. The Inversion of Control is
limited to the container invoking callback methods that application code can use to obtain
resources.
依赖查询, 容器会提供一种回调机制到组件, 通过上下文查询的方式能够拿到这个组件.
EJB 和 Avalon 就是典型的框架, 现在都不太流行了.
Dependency Injection:
Components do no look up; they provide plain Java methods enabling the container to resolve dependencies. The container is wholly
responsible for wiring up components, passing resolved objects in to JavaBean properties or
constructors. Use of JavaBean properties is called Setter Injection; use of constructor arguments is called Constructor Injection.”
依赖注入, 组件不需要被查找, 通常由容器帮我们自动注入来做一些事情, 或者我们手动注入.
EJB 3.0其实也已经实现了, spring更不必说.
IoC和DI的区别
DI只是IoC的一种实现方式, 实际上我们也看到了, 实现策略多着呢.
本文探讨了IoC(控制反转)在面向对象编程中的多种实现策略,包括服务定位(如JNDI)、依赖注入(构造器注入、setter注入)、接口注入和模板方法设计等。重点介绍了EJB3.0及Spring如何应用这些策略,并对比了DI与IoC的区别。

被折叠的 条评论
为什么被折叠?



