Understanding about Dependency Injection

Searching on Google, you can see that: there are a lot of tutorials about the Dependency Injection, each one with difference style. Perhaps, some of you can perceive it quickly, someone is not. So, I would like to summarize again and try to write about it in the easy way to understand. (I will try my best 😀 ).

The main ideas of Dependency Injection is: you don’t depend on anyone and no one depend on you. I will call you when I need and you too.

Let me talk more specific about it!

Someday in the past, I usually wrote my code like below:

Assume, you have an object Circle, this object has a method named draw() as below:

Now, I want to use this object to draw a circle, I will initialize the object Circle within the constructor and I will write the code as below:

Obviously, you see my object, Drawing, is depending on your object Circle (that means I am depending on you), because every time I run the application, the object Drawing must keep the information of the object Circle. This is the first drawback of this code.

The second drawback is: if in the future, I want to draw a triangle, I must declare again other object to satisfy my needs. This is cause the object Drawing will constantly changing according the needs.

So, how can we resolve this drawbacks?

The second drawback can resolve by using the interface. Your object Circle will implement an interface named Shape, details as below:

In the future, if I want to draw a triangle, I only need create new class and implement the interface Shape.

For the first drawback, Dependency Injection will resolve it.

Let see how Dependency Injection can resolve this problem, I will modify the object Drawing as below:

As you can see, if I only need my object Drawing prepare the tool to drawing, I don’t need to call to your object Circle, code will be:

After preparing complete, I will need you to draw a circle, I will call you:

Actually, maybe you already worked on the code but you didn’t know, this is Dependency Injection.

Add Comment