开发者

Dependency Injection mechanism

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜