Design Patterns in Java

Dependency Injection 

The main purpose of dependency injection is to promote loose coupling.


Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object.
Without Dependency Injection (DI):
class Car{
  private Wheel wh= new FirestoneWheel();
  private Battery bt= new AmaronBattery();

  //The rest
}
Here, the Car object is responsible for creating the dependent objects.
What if we want to change the type of its dependent object - say Wheel - after the initial FirestoneWheel() punctures? We need to recreate the Car object with its new dependency say MichelinWheel(), but only the Car manufacturer can do that.
Then what does the Dependency Injection do us for...?
When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.
After using dependency injection:
Here, we are injecting the dependencies (Wheel and Battery) at runtime. Hence the term : Dependency Injection.
class Car{
  private Wheel wh= [Inject an Instance of Wheel (dependency of car) at runtime]
  private Battery bt= [Inject an Instance of Battery (dependency of car) at runtime]
  Car(Wheel wh,Battery bt) {
      this.wh = wh;
      this.bt = bt;
  }
  //Or we can have setters
  void setWheel(Wheel wh) {
      this.wh = wh;
  }
}

Advantages of Dependency Injection
1. Loose coupling between components
2. If an object operates on their dependencies by their interface not by implementation then compile time dependency can be swapped out with Dependency Injection

Credits to http://ganeshtiwaridotcomdotnp.blogspot.com

No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days