Description
The Factory Method design pattern is one of the Creational Design Patterns, which is widely used in JDK, Spring, and Struts.
- It is used to create objects without exposing the creation logic to the client and refer to the created object using a common interface.
- It is used when we have a superclass with multiple subclasses, and one of the subclasses must be returned based on the input.
- It is one of the most used design patterns in Java.
Implementation in Java
Let's follow the below approach to implement this design pattern in Java.
- Create a class and make it an interface.
- Create multiple subclasses and implement the above interface.
- Create a factory that contains a method, which invokes a method from the interface to create an object of any of the subclasses types using an input.
Step 1: Create an interface.
Shape.java
public interface Shape {
void draw();
}
Step 2: Create multiple concrete classes, all implementing the same interface.
Reactangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
Step 3: Create a factory with a method that generates an object of a concrete class, based on given information.
ShapeFactory.java
public class ShapeFactory {
//Method to get an object based on the type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
Step 4: Generate concrete class objects by invoking the Factory method.
public class FactoryPatternDemo {
public static void main(String[] args) {
//Get an object of Factory
ShapeFactory shapeFactory = new ShapeFactory();
//Get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
//Get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
//Get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
Step 5: Execute the code to verify the output.
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
Overall
We now know about the Factory Method design pattern and its use cases.