Dependency Injection and Service Locator Design Pattern
Posted by sirajq on March 2, 2011
Dependency Injection is the prime technique to decouple the client classes from their dependent objects. DI makes the application, configurable, testable, flexible and easy to maintain. Client that depend on the service object for some functionality or data does not need to know the implementation details of the service object. Service object is expose to the Client through constructor, setter or properties. No changes is required at client side even if there is change in the service object because both of them are loose coupled.
Example :
class CDPlayer
{
protected CD _cd;
function CDPlayer(string sType)
{
switch (type)
{
case ‘Song’
_cd = new SongCD();
case ‘English’
_cd = new ThemeCD()
}
}
}
}
cdPlayer = new CDPlayer(“Hindi’)
In the above example, dependent object HindiCD and EnglishCD is strongly coupled with Client object CDPlayer object. Problem is client object always need to know the implementation details of the dependent object like constructor type and parameters details of the dependent object. Also, any change in the dependent object lead to change in the client object.
Here is the implementation of DI in the above example:
class CDPlayer
{
protected ICD _cd;
function CDPlayer(ICD)
{
_cd = CD;
}
}
SongCD oSongCd=new SongCD()
CDPlayer cdPlayer=new CDPlayer(oSongCd)
Service Locator is an alternative approach for promoting loose coupling in the application but it does not require injection of dependence through interface, constructor or properties. The service locator relies on the creation of the class called Service Locator that knows how to create the dependence of other type.