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:
Create an interface.
Shape.java
|
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
|
Use the Factory to get object of concrete class by passing an information such as type.
FactoryPatternDemo.java
|