What is Dependency Injection??
Let's start by answering this very first question with a simple example:
Suppose you want the build a Car, so what are the things required to build a Car?
Engine, Wheels, Tyres etc. Hence these components are called dependencies as they are required to build a Car.
Now considering the example and will try to use it in our daily coding problems.
We have a class Car, which needs a reference of Engine class to work.
There are two major ways to get an object of the Engine class:
1. Class Car should create the object and initialize its own instance of Engine Class. For Example
class Car {
private Engine engine = new Engine();
public void startCar() {
engine.start();
}
}
class MyApp {
public static void main(String[] args) {
Car car = new Car();
car.startCar();
}
}
This approach has a few problems:
a. It will make the Car class difficult to do unit testing. Suppose you want to use Electric Engine or Diesel Engine then you have to create two Car classes which is not a good practice.
b. You won't be able to see the required components to create Car class from outside.
2. Supply the Engine Class object as a parameter from outside, when a Car class is constructed. For example.
class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void startCar() {
engine.start();
}
}
class MyApp {
public static void main(String[] args) {
Engine engine = new Engine();
Car car = new Car(engine);
car.startCar();
}
}
class Car {
private final Engine engine;
private final Wheels wheels:
private final Steer steer
public Car(Engine engine, Wheels wheels, Steer steer) {
this.engine = engine;
this.wheels = wheels;
this.steer = steer;
}
public void startCar() {
wheels.installed();
steer.assembled();
engine.start();
}
}
class MyApp {
public static void main(String[] args) {
Engine engine = new Engine();
Wheels wheels = new Wheels();
Steer steer = new Steer();
Car car = new Car(engine, wheels, steer);
car.startCar();
}
}
Comments
Post a Comment