Dependency Injection的优点及适用范围

Dependency Injection (DI) 就是在类之间的互相引用,都采用Interface来代替。后台有Container,每个Interface包含一个Object,实际上这是一个Singleton的概念,所以在使用Singleton的时候,要避免使用DI,虽然DI支持非Singleton,但是感觉逻辑上不太符合常理。
http://tutorials.jenkov.com/dependency-injection/dependency-injection-benefits.html
优点:
A. 减少依赖关系
通过Interface互相联系,这样两个组件之间关联少一些。
B. 更加方便重复使用
只要是Interface相同,组件可以在不同的场合中重复使用。
C. 更容易测试
Test 的代码不需要和使用代码有任何关联,设置好Container,然后组件就自动生成。与正常运行,完全相同的测试环境,不需要考虑构造函数等等。
D. 更容易阅读
只需看Interface即可,一旦测试封装结束后,不需要读里面的代码。
E. 减少Dependency Carry
就是如果在最底层的引用某个变量,需要从最顶层一点点传递下来,如果用DI,就可以跳过中间部分。这个说得是Singleton,如果顶层的变量有一些特定的值,无法从Container中生成的话,就没必要了。
什么时候适合使用呢?
http://tutorials.jenkov.com/dependency-injection/when-to-use-dependency-injection.html
还是先说,什么时候不适合吧?
A。永远不会有不同的Implementation的时候
B. 永远不会有不同的Configuration的时候
适合的情形:
同一个Dependency给多个Component
同一个Dependency有多个不同的Implementation,如果要改换的话,直接去Registar里边改即可。
同一个Implementation给不同的Configurations
需要Service的情形。
笼统的说,就是需要Service,一对多,多对一几种情形。一对一,不会改变的时候,不要用DI。

Editorial Reviews Product Description Dependency Injection is an in-depth guide to the current best practices for using the Dependency Injection pattern-the key concept in Spring and the rapidly-growing Google Guice. It explores Dependency Injection, sometimes called Inversion of Control, in fine detail with numerous practical examples. Developers will learn to apply important techniques, focusing on their strengths and limitations, with a particular emphasis on pitfalls, corner-cases, and best practices. This book is written for developers and architects who want to understand Dependency Injection and successfully leverage popular DI technologies such as Spring, Google Guice, PicoContainer, and many others. The book explores many small examples of anchor concepts and unfolds a larger example to show the big picture. Written primarily from a Java point-of-view, this book is appropriate for any developer with a working knowledge of object-oriented programming in Java, Ruby, or C#. About the Author Dhanji R. Prasanna is an Enterprise Java consultant for technologies such as EJB3, JBI, JSF, Guice, Spring, HiveMind, and PicoContainer. He is a co-author of the Bean Validation (JSR-303), JAX-RS (JSR-311), Servlet 3.0 (JSR-315), and JavaServerFaces 2.0 (JSR-314) specifications. He is also co-author of the Java EE 6.0 (JSR-316) platform specification, which is the next edition of J2EE. Product Details * Paperback: 352 pages * Publisher: Manning Publications; 1 edition (August 28, 2009) * Language: English * ISBN-10: 193398855X * ISBN-13: 978-1933988559 * Product Dimensions: 9.1 x 7.4 x 0.8 inches
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值