Jobs
Blogs
Courses
Mentorship
Partners
For Employers
e2e logo

Factory Design Pattern

mac

Factory Design Pattern

Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface

Where We Use Factory Design Pattern:

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class. 

Why We Use Factory design Pattern:

Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. 

Implementation:

Factory Pattern UML Diagram 



Step 1

Create an interface.

Shape.java

 

Step 2

Create concrete classes implementing the same interface.

Rectangle.java


Square.java




Circle.java





 Step 3

Create a Factory to generate object of concrete class based on given information.

ShapeFactory.java





Step 4

Use the Factory to get object of concrete class by passing an information such as type.

FactoryPatternDemo.java