开发者

Dependency Injection mechanism

开发者 https://www.devze.com 2022-12-25 19:53 出处:网络
The advantage of inversion of contro开发者_运维问答l is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obt

The advantage of inversion of contro开发者_运维问答l is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

what does it mean actually ?


A good example of IoC is database mocking. While you're writing an application, you may need to persist objects for retrieval or use at some later point in time. Well, to abstract away the database, you create an interface with a method like this:

Interface DbSaver
+void save( MyObject myObject )
+MyObject load( String id )

Without IoC, you would have something like this:

DbSaver saver = new DefaultDbSaver();

or, you would just define an implementation, and access it as a singleton (which initially seems appropriate for a database manipulation object):

MyDbSaver saver = MyDbSaver.getInstance();

With IoC, you can switch the implementation of DbSaver without even recompiling your application (at least Spring provides this). That is, without changing any code, you can choose to use one implementation over another. With database access objects, the most common thing to do is create a default implementation which stores everything in memory. As you finalize your database design, structure, or technology, you can continue to build your application without worrying about how data gets persisted. You just work within the interface.

In this manner, the business objects are decoupled from database integration, which has the huge benefit of allowing both pieces to be developed in parallel.

0

精彩评论

暂无评论...
验证码 换一张
取 消