Spring – When to Use Factory Design Pattern Instead of Dependency Injection
Prerequisite: Factory Pattern vs Dependency Injection
Factory Design Pattern and Dependency Injection Design both are used to define the interface-driven programs in order to create objects. Dependency Injection is used to obtain a loosely coupled design, whereas the Factory Pattern adds coupling, between objects, factories, and dependencies. In this article, we will discuss when to use Factory Pattern over Dependency Injection.
In Dependency Injection, it is used for loosely coupled software components, It is not aware of any container or factory for creating of bean and is only aware of the dependency this makes the class easier for testing. The container (IOC contains in case of spring) manages object creation and its lifetime and also injects dependencies to the class.
In Factory Design, it creates various instances of a class without necessarily knowing what kind of object it creates or how to create it. The client is responsible for managing the factory class and to call the getInstance() method to create an instance of the class. This also makes the unit testing difficult as you would need a factory object in order to unit test.
When to use Factory Design
The Factory Pattern Design is mainly used in the following situations:
- A class does not know the type of object before its creation.
- A class requires its subclasses to specify the objects it creates.
- You want to localize the logic of your program to instantiate an instance of the class.
- It is useful when you need to abstract the creation of an object away from its actual implementation.
Please Login to comment...