Open In App

Spring – When to Use Factory Design Pattern Instead of Dependency Injection

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example:

Java




public class FactoryProduct{
        
    // Instance of OperatingSystem
    private OperatingSystem OS;  
        
    public void setAddress(Address address){  
        this.address=address;  
    }  
}


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.

Example:

Java




// Dependent class
public class FactoryProduct{
  
    public static void Main(String[] str){
        // Instance of OperatingSystemFactory class
        OperatingSystemFactory osfactory = new OperatingSystemFactory();
        // Getting the instance    
        OperatingSystem obj = osfactory.getInstance("windows");
        obj.cpu();
    }
}


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. 


Last Updated : 27 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads