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.
OperatingSystemFactory osfactory =
OperatingSystem obj = osfactory.getInstance(
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.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course
and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks