Difference between dependency injection and factory pattern?

Difference between dependency injection and factory pattern?
--------------------------------------------------------------
What is difference between factory pattern and dependency injection or difference between sprint IOC and factory pattern? are some of the frequently asked quesiton in Java irvs. Though both factory pattern and dependency injection might look similar, there is a fundamental difference between them. Factory pattern takes responsibility of creating object, while dependency injection inverse the process how an object gets his dependency, it transfer that responsibility to an external party e.g. Spring IOC transfer object creation and management functionality to the IOC container. In other words, If your use Factory pattern then your object has to retrieve dependency by himself, but in case of dependency injection, dependency will be injected to the object by container or whoever manages that object.

Advantages of Dependency Injection over Factory Pattern

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.


You might also like.


In short, though both Factory pattern and DI helps object creation, DI is much better than Factory. With DI you get better decoupling of object and its dependency. Dependency injection also makes unit testing easier, which is very important to keep quality control in check. BTW, nothing comes free, in order to use dependency injection you need a container e.g. Spring IOC, while you can use Factory pattern by your own. You also need to provide configuraiton to initialize object and inject dependency, like one we use with Spring to initialize beans e.g. aplicatoin-Context.xml

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.