Factory Design Pattern Using Java

Factory Design Pattern By Shubham Wankhede

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?

Why We Should Use the Factory Design Pattern?

Problems with hard coding object creation :

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 ?

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