Factory design pattern belong to the Creational design pattern category which explain how the objects are created. Factory Design Pattern comes with different flavors and we use the flavor as per our convenience. The very common example of Factory design pattern can be found in Spring. Creation of beans in Spring container is done using Factory design pattern only.

The implementation is really simple.

  • Create one class which will decide one what condition you need to create  what kind of object,
  • Return that newly created object.

But how

interface Shape {
    public void show();
}

class Circle implements Shape {
    public void show() {
       System.out.println("Its Circle");
    }
}

class Square implements Shape {
    public void show() {
       System.out.println("Its Square");
    }
}

class ShapeFactory {
     public Shape getShape(String shape) { 
        if ("Circle".eqaulIgnoreCase(shape)) {
             return new Circle();
        } else if("Square".eqaulIgnoreCase(shape)) {
             return new Square();
        }
     }
}

public class MainApplication { 
    public static void main(String[] args) { 
       ShapeFactory factory = new ShapeFactory();
       Shape circle = factory.getShape("circle");
       Shape square = factory.getShape("square"); 
       
       circle.show(); // Will print 'circle'
       square.show(); // Will print 'square'
    }
}

There are some precautions as well while using factory design patterns, which we may face in the form of ClassCastExceptions.

Please note the procedural switch-case implementation is the simplest but violates the OCP principle and is used in this example only to explain the theory.

Hope this clears your doubt!!