More on Dependency Injection

Sometime back I talked about dependency injection. Dependency injection is a design pattern that implements inversion of control principal. That is, you take out a dependency from within a class and inject it from outside.

So lets say there are 2 classes, Employee and Address, say Employee is dependent on Address

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

address=new Address(‘some values here’);

}

}

Here we are leaving the responsibility of creating the address with Employee class. Using DI (Dependency Injection) we will pull out this responsibility of creating the address object from Employee class and give it to calling/initializing class/container.

There are 2 ways to implement this DI concept

1. Through constructor:

class Employee{

public Address address;

Employee(Address address)

{

this.address=address;

}

}

2. Using a setter method:

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

}

public void setAddress(Address address)

{

this.address=address;

}

}

Lets make it a bit more interesting. Say we have a AddressFactory which can create either a LocalAddress or PermanentAddress. Both LocalAddress and PermanentAddress implement Address Interface.

In case of non DI scenario

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

//check if employee has local address

address=new AddressFactory.getAddress(“LocalAddress”);

//else case get permanent address

}

}

In this case DI becomes more useful as Employee class does not need to worry about the type of address which will be provided by calling class or container. No need to change the code given for DI implementation, it will work fine.