Monday, May 10, 2010

Inversion of control- Spring



It is highly recomended to reduce the dependancies in our classes since it is contradict with the object oriented design pattern.As an instant think you need to get some service from a out side class. So you need to create object of that class and call it.So your code is highly depends on that class.(tightly coupled). another problem that pop up due to this dependancy is we cannot simply chage the properties(of out sider class - using setters) and run the system.To do so we need recompile the project and run.
Inorder to avoid those kind of short commings IOC concept is introduced.

concept :
lets say ther is a class DocumentCreator.And it has subclasses PdfDocCreator and HtmlDocCreator.In our class we are going to get a service from PdfDocCreator or HtmlDocCreator.Then the dependancy derection is towards to DocumentCreator,HtmlDocCreator and PdfDocCreator.That means our class is tightly coupled with those three classes.



To avoid this we can simply define interface instead of DocumentCreator class and implement it for PdfDocCreator and HtmlDocCreator.
Then inorder to get a service from above class structure we can use that interface.Then the dependancy direction is changed.(It means usage of PDf or Html is depends on our class)

2 comments:

  1. In spring they have use this concept and introduced container concept.Container handles all object creation part and the life cycle of the objects.So it is the containers respocibility to determine how the objects should be created and when the objects should be created.Here actually Spring is depend on what we need and he is inverting the dependancy to his side and let others free from being tightly coupling.

    ReplyDelete