we use factory design pattern in lot of scenarios to get the object of a java class by passing some inputs,
example here, In spring framework we use the getBean(<beanId>) method to get the object of the spring bean which we have configured in our application.
in the above code spring framework uses factory design pattern internally to create the object of spring bean configured dynamically and return the same.
but most of the time we are not aware when we should use the factory design pattern or why to use the factory design pattern, in this article we will going to understand about this.
When should we create Factory Design Pattern?
- when your class cannot anticipate for which class it has to create the object from the group of related classes i.e it is difficult to anticipate for which class to create the object in that particular situation.
- when you want to hide/abstract the object creation process i.e you don’t want to give headache to client about complex object creation process.
- when you want to create the object of possible class based on data provided.
Why We Should Use the Factory Design Pattern?
Problems with hard coding object creation :
- whenever we create any java class object we need to satisfy all of it’s dependencies and hence need to write lot of complex code every time we want to create the object of that class
- if this class object is need to be created multiple time, it creates a boiler plate code
- if we write the object creation code i.e we just hard code the object creation and suppose instead of that same object we need the other implementation of it’s super class.
Solution with Factory Design Pattern : as we can see in above problems when we go for hard coding of object creation, we can use the factory design pattern to solve this issue.
In factory design pattern we create a factory which instantiate one of the several sub classes or other classes based on the data that is supplied at runtime.
How we can create the Factory Design pattern ?
- create a factory class,
- write a static factory method which returns one of the several related class object based on the inputs provided.
Suppose you want to create object of either Student class or Employee class based on the input ‘student’ or ‘employee’ which is provided at runtime, both classes has a super type as Person.
the factory Design pattern implementation can be written as below.
The more detailed example of above diagram is given in the below specified GitHub link