Factory Design Pattern Using Java

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.

iocContainerObject.getBean(“beanId”);

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?

  1. 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.
  2. 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.
  3. 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 :

  1. 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
  2. if this class object is need to be created multiple time, it creates a boiler plate code
  3. 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 ?

  1. create a factory class,
  2. write a static factory method which returns one of the several related class object based on the inputs provided.

Example :

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

https://github.com/WankhedeShub/DesignPatterns

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store