Dependency Injection or Dependency Inversion is a design pattern to decouple objects to overcome the dependency relation in objects. Say there are objects tied to each other for example there is a Drawing application.
Lets say there are two Circle and Triangle Classes which has a draw method in both classes. So when ever I want to use the draw method in my application I have to call the method as below specifically saying the object type.
Circle circle = new Circle();
circle.draw();
Triangle triangle = new Triangle();
triangle.draw();
Using Polymorphism
Polymorphism Example |
Introducing Shape interface or the parent class called Shape, both the draw methods in the Circle and Triangle Classes will override the draw method in the Shape Class.
Removing Dependency (Method Parameter)
To remove the dependency we can introduce a drawMethod() which will take shape as the parameter. Since both Circle and Triangle classes are inherited the dependency have been removed.
public void drawMethod(Shape shape){
shape.draw();
}
What ever object pass into the drawMethod() it will draw the shape accordingly. But still we haven't fully solve the problem.
Removing Dependency (Using Drawing Class)
public class Drawing{
private Shape shape;
public void setShape(Shape shape){
this.shape = shape;
}
public void drawShape(){
this.shape.draw();
}
Now the advantage of having this Drawing class is that it if fully independent from the type of the Shape. As long as the passed variable is inherited from the Shape Class. The idea is you are separating all the dependency out of a class. If the object you have to draw you don't have to care because the class Drawing has no idea of the type of the object which you are drawing. Drawing class doesn't holding the relationship. Dependency is injected through a different class to the Drawing class.
So to use the Drawing Class
Triangle triangle = new Triangle();
drawing.setShape(triangle);
drawing.drawShape();
Dependency is not hard coded to the class. It is actually injected by an entity outside the class. The Spring Framework makes it very easy to use this dependency Injection so before hand it's better you understand these concepts properly.
No comments:
Post a Comment