Dependency Injection ( DI ) and Factory pattern might look related to each other but there is a difference between them . Factory take the responsibility of creating an object while DI inverse the process of how an object obtains the dependencies . DI gives the responsibility of injecting dependencies to an external entity.
Example :
1. While using a factory , the dependent class Foo is responsible for creating the instance of its dependency Bar . In the below example we can see that Foo is calling the static method ( getInstance() ) of class BarFactory for instantiating Bar.
2. With DI , Foo is no more responsible for resolving the dependencies by its own . An external entity , for example spring container is responsible for instantiating and injecting the instance Bar in Foo class .
Advantages of DI :
1. Better decoupling of classes .
2. Better Unit testing . Now it is easier to inject mock implementation of the services into the object being tested.
Example :
1. While using a factory , the dependent class Foo is responsible for creating the instance of its dependency Bar . In the below example we can see that Foo is calling the static method ( getInstance() ) of class BarFactory for instantiating Bar.
public class Foo { private Bar bar = BarFactory.getInstance(); public void doStuff() { bar.doSomething(); } }
2. With DI , Foo is no more responsible for resolving the dependencies by its own . An external entity , for example spring container is responsible for instantiating and injecting the instance Bar in Foo class .
public class Foo { private Bar bar; /** * DI container uses the constructor to inject * the dependency in Foo class. */ public Foo(Bar bar) { this.bar = bar; } public void doStuff() { bar.doSomething(); } }
Advantages of DI :
1. Better decoupling of classes .
2. Better Unit testing . Now it is easier to inject mock implementation of the services into the object being tested.
No comments :
Post a Comment